AndroidPub
Published in

AndroidPub

Android — Adding badge or count to the navigation drawer

Navigation drawer in an app like Gmail will have a badge or count value in its row element. Here is a simple way to add them.

Navigation drawer with badges

Android Studio (latest version) will allow us to create ‘Helloworld’ apps with material design guidelines. While creating a new android project, choose “Navigation Drawer Activity”.

Studio will now create an Activity with a navigation drawer. Follow the steps below to add the badges

Step 1 : Adding “actionViewClass” attribute to the navigation drawer menu

After creating the ‘Helloworld’ app with Navigation Drawer, look for the file ‘activity_main_drawer.xml’ (i.e. youractivityname_drawer.xml)under the folder “Menu” in the project hierarchy view.

Identify the group item and add “app:actionViewClass=android.widget.TextView” as given below:

Step 2 : Declare the Navigation Drawer menu item and initialize the item with the badge value

In your main Activity, declare the menu item of the Navigation Drawer as given below

//Create these objects above OnCreate()of your main activity
TextView slideshow,gallery;
//These lines should be added in the OnCreate() of your main activity
gallery=(TextView) MenuItemCompat.getActionView(navigationView.getMenu().
findItem(R.id.nav_gallery));
slideshow=(TextView) MenuItemCompat.getActionView(navigationView.getMenu().
findItem(R.id.nav_slideshow));
//This method will initialize the count value
initializeCountDrawer();

initializeCountDrawer() can be called where ever it’s required. It can also be used to update the count or badge value in the navigation drawer menu item.

private void initializeCountDrawer(){    //Gravity property aligns the text
gallery.setGravity(Gravity.CENTER_VERTICAL);
gallery.setTypeface(null, Typeface.BOLD);
gallery.setTextColor(getResources().getColor(R.color.colorAccent));
gallery.setText("99+");
slideshow.setGravity(Gravity.CENTER_VERTICAL);
slideshow.setTypeface(null,Typeface.BOLD); slideshow.setTextColor(getResources().getColor(R.color.colorAccent));
//count is added
slideshow.setText("7");
}

On adding the above method, run the app. Et voila !!

A simple badge count will be displayed on the ‘gallery’ and ‘slideshow’ menu item of the Navigation Drawer.

Dynamic badge values

If you need the dynamic badge values, like updating the value from an API call or SQLite database, create a reusable method and update it on the OnStart() or OnResume() method of your Activity.

Complete source code will be found in the following link: https://github.com/Hariofspades/NavigationDrawerLabel

--

--

The (retired) Pub(lication) for Android & Tech, focused on Development

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store