This question already has an answer here:
- How to get text on an ActionBar Icon? 4 answers
I have a menu item in the action bar. Along with the menu item image, I need to show some number associated with it which will change often. I am not using Action bar sherlock. I don't want to use that. Other than this everything else just works fine. In the shown image, the white icon color icon is mine. I need to generate the number with the red color background dynamically. How can I do that in Android?
Here is the sample image:
Update:
I have this menu item in my menu.xml. This should work like a notification menu item which shows the number of notification count. I set the menu icon like,
menuItem.setIcon(image);
Now, on top of the menu item I need to place one text view which has the total count of notifications.
is it possible to implement this functionality with viewbadger? Github url
I discovered how to add an actionView to a menu item and retrieve as set values to the view in code.
See here: https://stackoverflow.com/a/16648170/857681
Here is one thing you can try:
Create a custom
Drawable
that paint you image in the background and text on top of the image. Check out this post for sample.Then set this
Drawable
as theMenuItem
background dynamically...After a lot of trying of nearly all resources on SO I turned to blogs; succesfully. I want to share what worked for me (Api >= 13); source.
Let's start with the sweet code, the way it's used:
The
menu_my.xml
:This class that conveniently makes a
BadgeDrawable
; its appearance can be modified as well:This class that helps to set the number. I recommend implementing even more thods to set badge as date, etc:
And mui importante a drawable (like a layout) in
res/drawable
:Good lucks!
Use action view. It works with both: default
ActionBar
andActionBarSherlock
.Here is an example
With this approach you can just create your own
View
(by inflating some layout for example) and then do whatever you want (change background, change content, add another views dynamically if your action view is subclass ofViewGroup
etc.).