但是我面临的问题是,对于Android 4.0,应用程序崩溃了。我第一次启动应用程序,它完美,徽章设置然后,我点击图标。然后,应用程序向我显示购物车片段,当我点击后退按钮时,是应用程序给我空指针异常。 我正在学习本教程http://mobikul.com/adding-badge-count-on-menu-items-like-cart-notification-etc/
我发现问题来自这行代码:
LayerDrawable icon = (LayerDrawable) itemCart.getIcon();
因为当我拿到图标时,它是空的。在获取图标之前,我尝试使用此代码:
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) {
itemCart.setIcon(context.getResources().getDrawable(R.drawable.ic_menu_cart_icon));
}
但这不起作用。
这是我的ic_menu_car.xml:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:drawable="@drawable/ic_cart_empty"
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>
这是我的menu.xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" >
<item
android:id="@+id/cart_option"
android:orderInCategory="100"
android:title="@string/menu_cart"
android:icon="@drawable/ic_menu_cart_icon"
app:showAsAction="always" />
</menu>
代码:
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.home, menu);
MenuItem itemCart = menu.findItem(R.id.cart_option);
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) {
itemCart.setIcon(context.getResources().getDrawable(R.drawable.ic_menu_cart_icon));
}
LayerDrawable icon = (LayerDrawable) itemCart.getIcon();
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, R.color.js_pink);
}
badge.setCount(count);
icon.mutate();
icon.setDrawableByLayerId(R.id.ic_badge, badge);
}
有人有同样的问题吗?
答案 0 :(得分:1)
设置LayerDrawble.setDrawableByLayerID()
之后调用menu.setIcon();
参考以下示例代码:
private void setBadgeCount(MainNavigationActivity mainNavigationActivity,LayerDrawable icon,String count){
// 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(mainNavigationActivity);
}
badge.setCount(count);
icon.mutate();
icon.setDrawableByLayerId(R.id.ic_badge, badge);
itemCart.setIcon(icon);
}