Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic drawable icon for ActionBar menu item? (Android, ActionBarSherlock)

How can I dynamically update the icon for an ActionBar MenuItem to show a 'red badge' with a number? (conceptually similar to "unread message count')

I'm using ActionBarSherlock in my Android application, targeting API level 10+. My application is for mobile data capture and, sometimes, the user cannot immediately submit new data but must save it locally on the phone (e.g. when connectivity is poor).

Whenever there are 'unsubmitted' items stored locally on the phone, I'd like to show the user a menu item (in the Action Bar) so that they can click over to the UnsubmittedItems activity and trigger an upload manually.

Ideally, this menu item will have some graphical representation of the number of unsubmitted items (similar to how an email or sms app shows the number of unread messages as a badge). Currently, I'm just doing:

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

And this works, but two issues: I'd prefer to use the Icon and keep the Title as something intelligible ("Unsubmitted") and, also, I'd love to have some custom layout or design here, such as a red circle background behind the number.

Thoughts on how to accomplish this? So far my research suggest two possibilities:

  1. Use a level list drawable that is precreated for some range of numbers (e.g. 1, 2, 3... 10+) and then unsubmittedMenuItem.getIcon().setLevel( numUnsubmitted )
  2. Build the entire bitmap entirely dynamically, using the Bitmap and Canvas APIs

These are similar in the sense that I'm rendering the text into a bitmap (either offline like #1 or on the fly like #2) but it would be great to leverage the 'native' text rendering of the ActionBar if possible and simply insert a red circle behind it like in a TextView.

Is there some way to set a custom layout just for the icon drawable? (NOT a full actionLayout, just for the icon?)

like image 398
Mike Repass Avatar asked Oct 24 '12 21:10

Mike Repass


1 Answers

There are a lot of ways to do this:

  1. Use LayerDrawable and stack badge images on top of your icon image.
  2. Write a custom class which extends from Drawable and draws the icon and badge manually.
  3. Use a custom action item view with your icon in an ImageView with a TextView overlay for the badge.
like image 65
Jake Wharton Avatar answered Nov 18 '22 15:11

Jake Wharton