繁体   English   中英

如何在android中将BitmapDrawable转换为LayerDrawable

[英]How to cast BitmapDrawable to LayerDrawable in android

这是代码段。

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;
}

这是错误的

LayerDrawable icon = (LayerDrawable) item.getIcon();

BitmapDrawable无法强制转换为android.graphics.drawable.LayerDrawable

如何将BitmapDrawable转换为图层LayerDrawable?

编辑:添加setBadgeCount函数。

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);
}

您只能投出Drawable你得到item.getIcon()LayerDrawable如果它实际上是一个LayerDrawable ,即如果icon菜单定义属性引用一个定义的绘制layer-list

从你的文章mentionned:菜单定义( menu/menu_home.xml中的文章, menu/main.xml你的情况)

<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>

引用的图标( drawable/ic_menu_notifications )应该是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>

另外一个层应该有ic_badge作为id。 这是setBadgeCount()使用的setBadgeCount()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM