How to add an item to a menu group in NavigationView

前端 未结 3 535
伪装坚强ぢ
伪装坚强ぢ 2021-01-31 03:30

In a word game for Android I currently have a hardcoded menu inflated from left_drawer_menu.xml and consisting of 3 groups (my turn, opponent turn and finally other

3条回答
  •  面向向阳花
    2021-01-31 04:12

    On checking MenuItemImpl source code

         ...
         *    @param group Item ordering grouping control. The item will be added after
         *            all other items whose order is <= this number, and before any
         *            that are larger than it. This can also be used to define
         *            groups of items for batch state changes. Normally use 0.
         ...
    
        MenuItemImpl(MenuBuilder menu, int group, int id, int categoryOrder, int ordering,
            CharSequence title, int showAsAction) {
    

    So you should define ordering in your xml (give same order to items in one group and increment in each following group)

    
    
        
            
            
        
        
            
            
            
        
        .....
    
    
    

    and give an appropriate order value while adding the item in your code. So if you want to add the item at the end of first group, add it as:

    menu.add(R.id.my_move, Menu.NONE, 0, "Item1");
    

    and if you want to add to second group, add it as:

    menu.add(R.id.his_move, Menu.NONE, 1, "Item2");
    

    The problem with your code could be that all items in the xml have default orderInCategory 0 and so the new item gets added after all these items.

    UPDATE

    To add icon use setIcon method for MenuItem

    menu.add(R.id.my_move, Menu.NONE, 0, "Item1").setIcon(R.drawable.ic_stars_black_24dp);
    

提交回复
热议问题