Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

android - NavigationView menu items with counter on the right

The new NavigationView in the new Design Support Library works really great.

They use "menu-items" to display the options.

But how can I display a counter to the right of the menu item?

Like in this picture:

enter image description here

Or like in the GMail app.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Starting from version 23 of appcompat-v7 NavigationView supports action views, so it is quite easy to implement counter yourself.

  1. 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" />
    
  2. 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.

  1. 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...