NavigationView menu items with counter on the right

前端 未结 5 844
谎友^
谎友^ 2020-11-27 11:36

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

They use \"menu-items\" to display th

5条回答
  •  攒了一身酷
    2020-11-27 12:20

    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:

      
      
      
    2. Reference it in your drawer menu xml, i.e. menu/drawer.xml:

      
      

    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.

提交回复
热议问题