Adding Badge count on menu items like cart , notification etc

Updated 30 June 2023

Save

In every application, we decorate our MenuItem placed on ActionBar. Displaying of badge count not only decorate the ActionBar beautifully but also displays useful information like showing the number of items currently available in your cart or update you with unread notification.

We can create badge count using either a custom view or by adding a distinct drawable to display the each state of MenuItem.

Both the options have its pros and cons.

There is another approach using LayerDrawable which is more flexible and efficient than the former approaches.

Here’s what we’re going to do:

  1. Create a LayerDrawable to display MenuItem with a badge.
  2. Create a custom drawable let us called BadgeDrawable.
  3. Set badge on the menu item from our Activity.

LayerDrawable

A Drawable that manages an array of other Drawables. These are drawn in array order, so the element with the largest index will be drawn on top.It can be defined in an XML file with the

It can be defined in an XML file with the <layer-list> element. Each Drawable in the layer is defined in a nested<item>

i. Creating a layer drawable to display menu item on layer one and badge on top of it.

ic_menu_cart.xml

ii. Creating menu for our activity to display the count on the menu items.

main.xml

iii. Creating a flexible and efficient custom BagdeDrawable class to draw a view that looks like a count

BagdeDrawable.java

Setting up altogether

We can get the icon of the menu using getIcon() method.

Here is our method setBadgeCount(). We can pass LayerDrawable which we get from meniItem and setBadge from anywhere from the application.

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


39 comments

  • Mohan Kumar
  • Mohan Kumar
  • Mahendren
  • Kevin
    • Aman Gupta (Moderator)
  • Farhad
  • Sunny
  • Sok Heang Khun
  • Wesley Campos
  • Kuldeep Dubey
    • Shubham Agarwal
    • Manikandan
  • adi
  • Ari Garasuthan
  • Mostafa Anter
  • Rahul Pahuja
  • pavan
  • Prasanna
    • Shubham Agarwal
  • vikygeek
  • Ninte Shilpi
  • Somnath Pal
  • tofa riyadi
  • Jeevan Prasad
    • Vinod Kumar
      • Jeevan Prasad
        • Vinod Kumar
  • Jeevan Prasad
  • gokul kalagara
    • Shubham Agarwal
  • Srikanth Kancheti
    • Shubham Agarwal
  • Darshan J
    • Shubham Agarwal
    • Jawed Aftab
  • Jaydeep Joshi
    • Shubham Agarwal
  • Saurabh Awasthi
    • Shubham Agarwal
  • Start a Project


      Message Sent!

      If you have more details or questions, you can reply to the received confirmation email.

      Back to Home