如何在android中将BitmapDrawable转换为LayerDrawable

时间:2016-05-09 08:17:15

标签: 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);
}

1 个答案:

答案 0 :(得分:3)

如果实际Drawable,您只能将item.getIcon()的{​​{1}}投放到LayerDrawable,即LayerDrawable菜单定义中的{1}}属性引用由icon

定义的drawable

在您提到的文章中:文章中的菜单定义(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> 作为id。这是ic_badge

使用的图层