NavigationView menu items with counter on the right

前端 未结 5 847
谎友^
谎友^ 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 11:58

    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:

提交回复
热议问题