Add a MenuItem to Menu at specific position or group programmatically

断了今生、忘了曾经 提交于 2019-12-06 19:14:36

问题


I have a

<android.support.design.widget.NavigationView
  app:menu="@menu/drawer"
/>

with the following menu items:

<item
    android:id="@+id/main_item"
    android:icon="@drawable/ic_menu_main"
    android:title="@string/app_name"/>

<group
    android:id="@+id/some_group"
    android:checkableBehavior="single"/>

<item
    android:id="@+id/teams_item"
    android:icon="@drawable/ic_menu_teams"
    android:title="@string/teams"/>

Now I want to add an item either to the some_group or just below it.

I tried:

MenuItem mi = menu.add( R.id.soume_group, someId, NONE, "some name" );

or

MenuItem mi = menu.add( R.id.soume_group, someId, 2, "some name" );

but the items are added at the bottom of the menu.

How to fix my problem?

TIA


回答1:


You can use the orderInCategory to define the order

    <item
        android:id="@+id/main_item"
        android:icon="@drawable/ic_menu_main"
        android:orderInCategory="100"   
        android:title="@string/app_name"/>

    <item
        android:id="@+id/teams_item"
        android:icon="@drawable/ic_menu_teams"
        android:orderInCategory="1000"      
        android:title="@string/teams"/>

if you want to insert between main_item and teams_item you can use orderInCategory that is between

// 500 is between main_item(100) and teams_item(1000)
MenuItem mi = menu.add( NONE, someId, 500, "some name" ); 


来源:https://stackoverflow.com/questions/33971541/add-a-menuitem-to-menu-at-specific-position-or-group-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!