Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add items to menu group programatically in navigation view

I am trying to add menu items to menu group pragmatically but I found no way to do that. I am using Navigation View and added below mentioned menu:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/nav_lang_currency"
        android:title="" />

    <item
        android:id="@+id/nav_home"
        android:title="" />

    <group android:id="@+id/nav_refer" />

    <item
        android:id="@+id/nav_setting"
        android:title="" />

    <item
        android:id="@+id/nav_about_us"
        android:title="" />

    <item
        android:id="@+id/nav_logout"
        android:title="" />

</menu>

Everything looks good as mentioned.

I just want to add multiple menu items in nav_refer group at run-time as per business requirement but I found no way to do that.

I searched solution on SO but found no way to do that.

Kindly suggest me how to add multiple menu items in group at run-time.

like image 869
Geeky Singh Avatar asked Mar 31 '16 12:03

Geeky Singh


2 Answers

To add menu to a particular group, call this method Menu.add(int groupId, int itemId, int order, CharSequence title)

    Menu menu = navigationView.getMenu();
    menu.add(R.id.nav_refer, 123, Menu.NONE, "Title1");
    menu.add(R.id.nav_refer, 124, Menu.NONE, "Title2");
    menu.add(R.id.nav_refer, 125, Menu.NONE, "Title3");

Important : Initially if you have empty group then newly added items will appear in bottom, to solve this you need to mention orders for groups. add a attribute for all your groups android:orderInCategory="101"

like image 194
Bharatesh Avatar answered Oct 24 '22 10:10

Bharatesh


You can do something like this:

NavigationView navView = (NavigationView) findViewById(R.id.navView);
Menu menu = navView.getMenu();
SubMenu subMenu = menu.addSubMenu("sub menu");
subMenu.add("item 1");
subMenu.add("item 2");
subMenu.add("item 3");
like image 1
Rohit Arya Avatar answered Oct 24 '22 11:10

Rohit Arya