【问题标题】:ClassCastException: BitmapDrawable cannot be cast to LayerDrawableClassCastException:BitmapDrawable 无法转换为 LayerDrawable
【发布时间】:2016-05-04 02:40:33
【问题描述】:

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

    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

【问题讨论】:

标签: java android casting


【解决方案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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-26
    • 2020-05-11
    • 1970-01-01
    • 2023-02-02
    • 2016-06-30
    • 2016-01-14
    相关资源
    最近更新 更多