Adding Badge count on menu items like cart , notification etc
 

Adding Badge count on menu items like cart , notification etc

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.

Sample source code

  • Saurabh Awasthi

    Its works like charm….thanxx a lot for this useful tutorial….
    I have a question how to remove badge on click menu item for showing notification read???

    • Shubham Agarwal

      use this

      setBadgeCount(this, icon,”0″)

      This will set mWillDraw to false if the count is “0”. Thus This will not draw the badge or simply remove the badge.

  • Jaydeep Joshi

    please give me image resources like ic_cart and ic_menu_cart

  • Darshan J

    if (reuse != null && reuse instanceof BadgeDrawable) {
    badge = (BadgeDrawable) reuse;
    }
    else {
    badge = new BadgeDrawable(context);
    }

    here if I get reuse as null;the onDraw() method of BadgeDrawable is not called at all(so no badge) since the bounds are 0; how do I fix this; sometimes badge will get drawn as sometimes not and it entirely depends on reuse variable (if its null no badge and if its not null, I can see the badge).
    Thanks, any help will be greatly appreciated 😉

    • Shubham Agarwal

      Please check the edits we have updated the blog. If you are still having any issues let us know.

  • Srikanth Kancheti

    java.lang.ClassCastException: android.graphics.drawable.BitmapDrawable cannot be cast to android.graphics.drawable.LayerDrawable
    at com.example.srikanth.badgesample.MainActivity.onCreateOptionsMenu(MainActivity.java:26)

    Getting the above ClassCastException

    • Shubham Agarwal

      Please compare with the ic_menu_cart.xml file are you using LayerDrawable of BitmapDrawable. Please check edits and share your file if you are having any problem

  • gokul kalagara

    It Not getting in Nexus and Goto G2

    • Shubham Agarwal

      We have updated the blog. Does this work for other device. Because the problem may not be because of device.

  • Jeevan Prasad

    hi

  • Jeevan Prasad

    I am using this code but getting an error i.e java.lang.ClassCastException: android.support.v7.view.menu.MenuItemImpl cannot be cast to android.graphics.drawable.LayerDrawable

    • Vinod Kumar

      First you should inflate the menu and then

      MenuInflater inflater = getMenuInflater();
      inflater.inflate(R.menu.main, menu);
      MenuItem itemCart = menu.findItem(R.id.action_cart);
      LayerDrawable icon = (LayerDrawable)itemCart.getIcon();
      setBadgeCount(this, icon, “9”);
      return super.onCreateOptionsMenu(menu);

      • Jeevan Prasad

        Thank u vinod kumar

        • Vinod Kumar

          you are welcome …

  • i like it.
    thanks…

  • Ninte Shilpi
  • Somnath Pal

    How to change batch text in onCreate() using the method setBadgeCount?

  • Shubham Agarwal

    PLEASE CHECK THE SAMPLE SOURCE CODE https://github.com/mwshubham/AndroidBadgeDemo

  • vikygeek

    I have to change the number in the badge on a button click in a Fragment. Eg. When I click the “Add to Cart” Button the badge must get incremented. I got trouble in Sending the Arugument of LayerDrawable. I can’t fetch the menu while creating the LayerDrawable object in onCickEventListener() method. How to Do this?

  • Prasanna

    Can we use it using ImageButton instead of actionbar

    • Shubham Agarwal

      It’s a drawable so i am sure it will work for ImageButton as well

  • pavan

    Link to view the source code isn’t working. Please check?

  • Rahul Pahuja

    Thanks alot, very helpful article

  • Mostafa Anter

    thank you very much 🙂

  • Ari Garasuthan

    Thank You

  • adi

    link dead, please sent my email : [email protected]

  • Kuldeep Dubey

    Hello Thank you for the article. I used it and it was working very comfortably in API versions below 23. But in 23 and above the cart image gets expanded. Could you help. Image: https://i.stack.imgur.com/pG8Hc.png

    • Shubham Agarwal

      @kuldeepdubey:disqus first of all, it seems like you are setting badge below the cart icon.
      In case you are having problem with the badge setting badge bound in onDraw().
      This is a simple drawable i am not sure it is dependent on android api version.
      If you still have some problem please share sample git project reproducing the problem. We will help you out.

    • Manikandan

      @kuldeepdubey:disqus did you get solution to your problem. If so let me know. or kindly share at [email protected]

  • Wesley Campos

    Thank you. Me ajudou muito.

  • Sok Heang Khun

    Thank you very much.

  • Sunny

    it doesnot works in Android version jellybean or less than lollipop