2

error is generated on these code : setBadgeCount(this,icon ,"0");

here is my code:

  MenuItem itemCart = menu.findItem(R.id.action_cart);
    LayerDrawable icon = (LayerDrawable) itemCart.getIcon();

    // Update LayerDrawable's BadgeDrawable

    setBadgeCount(this,icon ,"0");
Jaydeep Joshi
  • 53
  • 1
  • 2
  • 11

2 Answers2

5

You get ClassCastException because your MenuItem returns not BitmapDrawable, you can create LayerDrawable from BitmapDrawable you get from MenuItem

According to this answer (https://stackoverflow.com/a/20138871/4142087), or official documentation you can do it this way:

BitmapDrawable iconBitmap = (BitmapDrawable) itemCart.getIcon();
LayerDrawable iconLayer = new LayerDrawable(new Drawable [] { iconBitmap });
setBadgeCount(this, iconLayer, "0");
Community
  • 1
  • 1
Anton Shkurenko
  • 4,301
  • 5
  • 29
  • 64
  • java.lang.NullPointerException is generated .. what should i do? – Jaydeep Joshi May 24 '16 at 04:56
  • public boolean onCreateOptionsMenu(Menu menu) { MenuItem itemCart = menu.findItem(R.id.action_cart); BitmapDrawable iconBitmap = (BitmapDrawable) itemCart.getIcon(); LayerDrawable iconLayer = new LayerDrawable(new Drawable [] { iconBitmap }); setBadgeCount(MainActivity.this, iconLayer, "9"); return true; } – Jaydeep Joshi May 24 '16 at 08:39
  • public static void setBadgeCount(Context context, LayerDrawable icon, String count) { BadgeDrawable badge; 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); } – Jaydeep Joshi May 24 '16 at 08:41
  • 1
    @JaydeepJoshi You forgot this : **getMenuInflater().inflate(R.menu.main, menu);** – Manish Gupta Apr 02 '18 at 05:51
1

Change the menu items icon drawable from vector drawable to layer-list. In the layer list you can include the vector items like this. Here the cart icon is a vector.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:drawable="@drawable/cart_icon"
        android:gravity="center" />
    <item
        android:id="@+id/ic_badge"
        android:drawable="@drawable/cart_icon" />
</layer-list>
Jay Patel
  • 89
  • 7