This is code snippet.
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the main; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
MenuItem item = menu.findItem(R.id.action_notifications);
LayerDrawable icon = (LayerDrawable) item.getIcon();
// Update LayerDrawable's BadgeDrawable
Utils2.setBadgeCount(this, icon, mNotificationsCount);
return true;
}
It is giving error in line
LayerDrawable icon = (LayerDrawable) item.getIcon();
BitmapDrawable cannot be cast to android.graphics.drawable.LayerDrawable
How to cast BitmapDrawable to layer LayerDrawable?
Edit : adding setBadgeCount function.
public static void setBadgeCount(Context context, LayerDrawable icon, int count) {
BadgeDrawable badge;
// Reuse drawable if possible
Drawable reuse = icon.findDrawableByLayerId(R.id.ic_badge);
if (reuse != null && reuse instanceof BadgeDrawable) {
badge = (BadgeDrawable) reuse;
} else {
badge = new BadgeDrawable(context);
}
badge.setCount(count);
icon.mutate();
icon.setDrawableByLayerId(R.id.ic_badge, badge);
}
You can only cast the Drawable you get from item.getIcon() to a LayerDrawable if it actually is a LayerDrawable, i.e. if the icon attribute in the menu definition references a drawable defined by a layer-list
From the the article you mentionned : the menu definition (menu/menu_home.xml in the article, menu/main.xml in your case)
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/action_notifications"
android:title="Notifications"
android:icon="@drawable/ic_menu_notifications"
android:showAsAction="always"/>
</menu>
The icon (drawable/ic_menu_notifications) referenced should be a layer-list :
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/ic_notification"
android:drawable="@drawable/ic_action_email"
android:gravity="center" />
<!-- set a place holder Drawable so android:drawable isn't null -->
<item
android:id="@+id/ic_badge"
android:drawable="@drawable/ic_action_email" />
</layer-list>
Also one of the layer should have ic_badge as id. This is the layer used by setBadgeCount()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With