无法在Android中将Drawable转换为LayerDrawable

时间:2017-02-09 12:47:31

标签: java android android-studio android-drawable classcastexception

我想在菜单项上显示通知徽章。我的代码是

onPrepareOptionsMenu()

    int cartSize = MyCart.getCartSize();
    MenuItem cartItem = menu.findItem(R.id.toolbar_ic_cart);

    if (cartSize > 0) {
        LayerDrawable icon = (LayerDrawable) cartItem.getIcon();
        NotificationBadgeCount.setBadgeCount(this, icon, String.valueOf(cartSize));
    } else {
        cartItem.setIcon(R.drawable.ic_cart_empty);
    }

菜单/ toolbar_menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/toolbar_ic_search"
        android:title="Search"
        android:icon="@drawable/ic_search"
        app:showAsAction="always" />

    <item
        android:id="@+id/toolbar_ic_cart"
        android:title="Cart"
        android:icon="@drawable/ic_cart_menu"
        app:showAsAction="always" />

</menu>

@绘制/ ic_cart_menu

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:drawable="@drawable/ic_cart_full"
        android:gravity="center" />

    <!-- set a place holder Drawable so android:drawable isn't null -->
    <item
        android:id="@+id/ic_badge"
        android:drawable="@drawable/ic_cart_empty" />

</layer-list>

这段代码对我来说很好。但升级支持库后,我在除Marshmallow之外的所有设备上都出现错误

以下行

出错
LayerDrawable icon = (LayerDrawable) cartItem.getIcon();

Lollipop上的错误。

java.lang.ClassCastException: android.support.v4.graphics.drawable.DrawableWrapperLollipop cannot be cast to android.graphics.drawable.LayerDrawable

Kitkat出错。

java.lang.ClassCastException: android.support.v4.graphics.drawable.DrawableWrapperKitkat cannot be cast to android.graphics.drawable.LayerDrawable

2 个答案:

答案 0 :(得分:1)

这是因为DrawableWrapperLollipopDrawableWrapperKitkatDrawableWrapperKitkat扩展到其他旧版本,依旧等等。但是,父类是Drawable而不是LayerDrawable 。这就是例外的原因。

答案 1 :(得分:1)

这些包装类都实现了DrawableWrapper,您可以从中获取原始的drawable:

import android.support.v4.graphics.drawable.DrawableWrapper;

...

    LayerDrawable icon = null;
    Drawable drawable = cartItem.getIcon();
    if (drawable instanceof DrawableWrapper) {
        drawable = ((DrawableWrapper)drawable).getWrappedDrawable();
    }
    icon = (LayerDrawable) drawable;