How to programmatically add a group to the navigation box

I have a navigation box in an Android app. I can add groups and elements to it using XML, however I need to add new groups to it programmatically.

For example, I have this XML:

<group android:checkableBehavior="single"> <item android:id="@+id/nav_camara" android:icon="@android:drawable/ic_menu_camera" android:title="Import" /> <item android:id="@+id/nav_gallery" android:icon="@android:drawable/ic_menu_gallery" android:title="Gallery" /> <item android:id="@+id/nav_slideshow" android:icon="@android:drawable/ic_menu_slideshow" android:title="Slideshow" /> <item android:id="@+id/nav_manage" android:icon="@android:drawable/ic_menu_manage" android:title="Tools" /> </group> 

How can I do this if this group has no elements and I need to add them by code?

If I use:

 Menu sistemas = navigationView.getMenu(); sistemas.add(Menu.FIRST, 1, 0, "Prueba"); 

The item is added as a menu under all parameters, and not as a group.

Regards, Jaime

+6
source share
1 answer

My best suggestion, if you want to stick with NavigationView, is this:

Set up your XML so that it contains any groups that you think you need to add dynamically and set them to invisible:

 <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity"> <group android:id="@+id/main_group"> <item android:id="@+id/nav_camara" android:icon="@android:drawable/ic_menu_camera" android:title="Import" /> <item android:id="@+id/nav_gallery" android:icon="@android:drawable/ic_menu_gallery" android:title="Gallery" /> <item android:id="@+id/nav_slideshow" android:icon="@android:drawable/ic_menu_slideshow" android:title="Slideshow" /> <item android:id="@+id/nav_manage" android:icon="@android:drawable/ic_menu_manage" android:title="Tools" /> </group> <group android:visible="false" android:id="@+id/second_group"> </group> <group android:visible="false" android:id="@+id/third_group"> </group> </menu> 

Then, when you need to show them or add dynamic parameters for these groups:

  Menu menu = mNavView.getMenu(); // Add items to the second group, and set to visible menu.add(R.id.second_group, 1, 100, "Item 1"); menu.add(R.id.second_group, 2, 200, "Item 2"); menu.add(R.id.second_group, 3, 300, "Item 3"); menu.setGroupCheckable(R.id.second_group, true, true); menu.setGroupVisible(R.id.second_group, true); // Add items to the third group, and set to visible menu.add(R.id.third_group, 4, 400, "Item 1"); menu.add(R.id.third_group, 5, 500, "Item 2"); menu.add(R.id.third_group, 6, 600, "Item 3"); menu.setGroupCheckable(R.id.third_group, true, true); menu.setGroupVisible(R.id.third_group, true); 

Just make sure that when you add your items, the item ID is different and the order in the category is the actual order in the entire menu of dynamic items.

+8
source

All Articles