这是代码 fragment 。
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);
}
最佳答案
您只能将从item.getIcon()
获得的Drawable
转换为LayerDrawable
,前提是确实 是 LayerDrawable
,即如果菜单定义中的 icon
属性引用由 layer-list
来自您提到的文章:菜单定义(文章中的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()
关于android - 如何在 Android 中将 BitmapDrawable 转换为 LayerDrawable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37110778/