NavigationView menu items with counter on the right
Starting from version 23 of appcompat-v7 NavigationView
supports action views, so it is quite easy to implement counter yourself.
Create counter layout, i.e.
menu_counter.xml
:<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="match_parent" android:gravity="center_vertical" android:textAppearance="@style/TextAppearance.AppCompat.Body2" />
Reference it in your drawer menu xml, i.e.
menu/drawer.xml
:<item ... app:actionLayout="@layout/menu_counter" />
Note that you should use app
namespace, don't try to use android
.
Alternatively you can manually set action view with MenuItem.setActionView()
method.
Find menu item and set counter:
private void setMenuCounter(@IdRes int itemId, int count) { TextView view = (TextView) navigationView.getMenu().findItem(itemId).getActionView(); view.setText(count > 0 ? String.valueOf(count) : null); }
Note, that you will need to use MenuItemCompat if you have to support Android 2.x versions.
My workaround was passing a SpannableString with a different background as new title of the MenuItem.
I known is not the best solution and it's not right-aligned but it works as a counter quite well. Something like this:
NavigationView navigation = (NavigationView)findViewById(R.id.navigation);
Menu menuNav = navigation.getMenu();
MenuItem element = menuNav.findItem(R.id.item5);
String before = element.getTitle().toString();
String counter = Integer.toString(5);
String s = before + " "+counter+" ";
SpannableString sColored = new SpannableString( s );
sColored.setSpan(new BackgroundColorSpan( Color.GRAY ), s.length()-(counter.length()+2), s.length(), 0);
sColored.setSpan(new ForegroundColorSpan( Color.WHITE ), s.length()-(counter.length()+2), s.length(), 0);
element.setTitle(sColored);
To improve the counter, here you can find a good answer to set the corners rounded
Example: