java.lang.ClassCastException: android.graphics.drawable.BitmapDrawable 不能转换为 android.graphics.drawable.LayerDrawable

Jay*_*shi 1 android android-studio

在这些代码上生成错误: setBadgeCount(this,icon ,"0");

这是我的代码:

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

    // Update LayerDrawable's BadgeDrawable

    setBadgeCount(this,icon ,"0");
Run Code Online (Sandbox Code Playgroud)

Ant*_*nko 5

你得到ClassCastException是因为你的MenuItem回报不是BitmapDrawable,你可以LayerDrawableBitmapDrawable你得到MenuItem

根据此答案(/sf/answers/1409721001/)或官方文档,您可以这样做:

BitmapDrawable iconBitmap = (BitmapDrawable) itemCart.getIcon();
LayerDrawable iconLayer = new LayerDrawable(new Drawable [] { iconBitmap });
setBadgeCount(this, iconLayer, "0");
Run Code Online (Sandbox Code Playgroud)