Dynamic shortcut for an ActionBar menu item? (Android, ActionBarSherlock)

How can I dynamically update an ActionBar menu item icon to show a “red icon” with a number? (conceptually similar to the "unread message count")

I use ActionBarSherlock in my Android application, focusing on API level 10+. My application is designed for mobile data capture, and sometimes the user can not immediately send new data, but must save it locally on the phone (for example, in case of poor connection).

Whenever “unspecified” items are stored on the phone that are stored locally on the phone, I would like to show the user a menu item (in the action bar) so that they can go to UnsubmittedItems activity and start the download manually.

Ideally , this menu item will have some graphical representation of the number of unexpected items (similar to how an e-mail or SMS application displays the number of unread messages as an icon). I am currently just doing:

unsubmittedMenuItem.setTitle( Integer.toString(numUnsubmitted) ); 

And it works, but two questions: I would prefer to use the icon and save the Title as something understandable ("Unsubmitted"), and, in addition, I would like to have some kind of custom layout or design here, for example, a red circle with a number.

Thoughts on how to do this? So far, my research has suggested two possibilities:

  • Use the drop-down list of levels that is preprocessed for a certain range of numbers (for example, 1, 2, 3 ... 10+), and then unsubmittedMenuItem.getIcon (). setLevel (numUnsubmitted)
  • Build the entire bitmap fully dynamically using the Bitmap and Canvas APIs.

They are similar in the sense that I pass the text to a bitmap (either offline, like # 1, or on the fly, like # 2), but it would be great to use a native ActionBar textual rendering, if possible and just paste the red circle behind it, as in TextView.

Is there a way to set a custom layout just for drawing an icon? (NOT the full Layout action, just for the badge?)

+7
source share
1 answer

There are many ways to do this:

  • Use LayerDrawable and create icon images on top of the icon image.
  • Write a custom class that extends from Drawable and draws the icon and icon manually.
  • Use a custom action view with your icon in ImageView with a TextView overlay for the icon.
+6
source

All Articles