Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an item programatically in navigation drawer menu

Tags:

I have a navigation drawer in my application. I want to add an option programatically in the second section of the navigation drawer's menu. The menu.xml is-

<group android:checkableBehavior="single">
    <item android:id="@+id/nav_connect_sensor"
        android:icon="@drawable/ic_action_bluetooth"
        android:title="Connect Bluetooth" />
    <item android:id="@+id/nav_take_tour"
        android:icon="@drawable/ic_action_video"
        android:title="Take a tour" />
    <item android:id="@+id/nav_my_stats"
        android:icon="@drawable/ic_action_bargraph"
        android:title="My Stats" />
</group>

<item android:title="@string/navigation_drawer_group_title"
    android:id="@+id/other_labels">
    <menu>
        <item android:id="@+id/nav_myAccountSettings"
            android:icon="@drawable/ic_settings"
            android:title="My Account" />
        <item android:id="@+id/nav_application_settings"
            android:icon="@drawable/ic_action_settings"
            android:title="Application Settings" />
        <item android:id="@+id/comparison"
            android:icon="@drawable/ic_swap_horiz"
            android:title="Compare"/>
        <item android:id="@+id/nav_help_and_feedback"
            android:icon="@drawable/ic_live_help"
            android:title="Help and Feedback" />
        <item android:id="@+id/nav_logout"
            android:icon="@drawable/ic_action_exit"
            android:title="Sign Out" />
    </menu>
</item>

For adding an option programatically-

    Menu menu = mNavigationView.getMenu();
    menu.add(0, Menu.FIRST, Menu.FIRST, "Players")
        .setIcon(R.drawable.ic_people);

This option is getting added at the last. How can I add the option in the third position i.e. below Application Settings

like image 580
Pratishtha Sharma Avatar asked Mar 29 '16 09:03

Pratishtha Sharma


2 Answers

Try this:

Menu.THIRD=3;

 Menu menu = mNavigationView.getMenu();
        menu.add(0, Menu.THIRD, 2, "Players")
                .setIcon(R.drawable.music_audio);
like image 174
Android Geek Avatar answered Nov 15 '22 05:11

Android Geek


You can use.

Menu menu = navView.getMenu(); // navView is NavigationView reference.
menu.add("Item 1");
menu.add("Item 2");
menu.add("Item 3");
like image 36
Yusuf Çakal Avatar answered Nov 15 '22 06:11

Yusuf Çakal