Search code examples
androidmenuitemandroid-navigationview

Add a MenuItem to Menu at specific position or group programmatically


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


Solution

  • 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" );