Issue
I want to display notification badge on menu item. My code is
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);
}
menu/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>
@drawable/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>
This code was working fine for me. But after upgrading support libraries, I am getting error on all devices except Marshmallow
Error in following line
LayerDrawable icon = (LayerDrawable) cartItem.getIcon();
Error on Lollipop.
java.lang.ClassCastException: android.support.v4.graphics.drawable.DrawableWrapperLollipop cannot be cast to android.graphics.drawable.LayerDrawable
Error on Kitkat.
java.lang.ClassCastException: android.support.v4.graphics.drawable.DrawableWrapperKitkat cannot be cast to android.graphics.drawable.LayerDrawable
Solution
Those wrapper classes all implement DrawableWrapper
, from which you can get the original 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;
Answered By - kris larson
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.