How to convert bitmapdrawable to layerdrawable in Android

This is a code snippet

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

It gives an error in the line

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

Bitmapdrawable cannot be cast to android.graphics.drawable.layerdrawable

How to convert bitmapdrawable to layerdrawable layers?

Edit: add setbadgecount function

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

resolvent:

If the drawable obtained from item. GETICON () is actually layerdrawable, that is, if the icon attribute in the menu definition references the drawable defined by layer list, it can only be converted to layerdrawable

In the article you mentioned: menu definition (menu / menu_home.xml in this article, menu / main.xml in your case)

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

The referenced icon (drawable / ic_menu_notifications) should be 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>

Similarly, one of the layers shall also have IC_ Badge as ID. this is the layer used by setbadgecount()

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>