How to cast BitmapDrawable to LayerDrawable in android -


this code snippet.

public boolean oncreateoptionsmenu(menu menu) {     // inflate main; adds items action bar if 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 giving error in line

layerdrawable icon = (layerdrawable) item.geticon(); 

bitmapdrawable cannot cast android.graphics.drawable.layerdrawable

how cast bitmapdrawable layer layerdrawable?

edit : adding 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); } 

you can cast drawable item.geticon() layerdrawable if actually layerdrawable, i.e. if icon attribute in menu definition references drawable defined layer-list

from the article mentionned : menu definition (menu/menu_home.xml in article, menu/main.xml in 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 icon (drawable/ic_menu_notifications) referenced should 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 place holder drawable android:drawable isn't null -->   <item       android:id="@+id/ic_badge"       android:drawable="@drawable/ic_action_email" /> </layer-list> 

also 1 of layer should have ic_badge id. layer used setbadgecount()


Comments

Popular posts from this blog

javascript - Laravel datatable invalid JSON response -

java - Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; -

sql server 2008 - My Sql Code Get An Error Of Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value '8:45 AM' to data type int -