ClassCastException:BitmapDrawable无法强制转换为LayerDrawable

时间:2016-01-27 08:40:26

标签: java android casting

我想在操作栏中添加徽章计数器并使其可点击

    getMenuInflater().inflate(R.menu.main_menu, menu);
    MenuItem item = menu.findItem(R.id.action_notifications);
    LayerDrawable icon = (LayerDrawable) item.getIcon();
    Utils2.setBadgeCount(this, icon, 2);
    return true;

错误:

java.lang.ClassCastException: android.graphics.drawable.BitmapDrawable cannot be cast to android.graphics.drawable.LayerDrawable

1 个答案:

答案 0 :(得分:-1)

正如@IntelliJ所述,这已经是answered

public Drawable geSingleDrawable(LayerDrawable layerDrawable){

      int resourceBitmapHeight = 136, resourceBitmapWidth = 153;

      float widthInInches = 0.9f;

      int widthInPixels = (int)(widthInInches * getResources().getDisplayMetrics().densityDpi);
      int heightInPixels = (int)(widthInPixels * resourceBitmapHeight / resourceBitmapWidth);

      int insetLeft = 10, insetTop = 10, insetRight = 10, insetBottom = 10;

      layerDrawable.setLayerInset(1, insetLeft, insetTop, insetRight, insetBottom);     

      Bitmap bitmap = Bitmap.createBitmap(widthInPixels, heightInPixels, Bitmap.Config.ARGB_8888);

      Canvas canvas = new Canvas(bitmap);
      layerDrawable.setBounds(0, 0, widthInPixels, heightInPixels);
      layerDrawable.draw(canvas);

      BitmapDrawable bitmapDrawable = new BitmapDrawable(getResources(), bitmap);
      bitmapDrawable.setBounds(0, 0, widthInPixels, heightInPixels);

      return bitmapDrawable;
}