I am trying to add new menu items to a submenu in the new Material Design drawer panel.
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
...
<android.support.design.widget.NavigationView
android:id="@+id/main_navigation"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/channel_list_header"
app:menu="@menu/menu_nav" />
</android.support.v4.widget.DrawerLayout>
I do have the @menu/menu_nav setup but now want to add new menu items:
NavigationView mDrawerList = (NavigationView) findViewById(R.id.main_navigation);
Menu menu = mDrawerList.getMenu();
Menu topChannelMenu = menu.addSubMenu("Top Channels");
topChannelMenu.add("Foo");
topChannelMenu.add("Bar");
topChannelMenu.add("Baz");
mDrawerList.invalidate(); // Trying to force a redraw, doesn't help.
The menu items from the @menu/menu_nav file are shown, but the newly added ones aren't. Any ideas how to do that?
This is how I manipulate the sub-menu item in NavigationView
1) Create menu.xml file
2) Manipulate the menu by calling this function
[Update 20-03-2016] Bug is resolved. So no need to worry.
[This below contetnt is outdated.]
Adding a dynamic menu to NavigationView is currently bug on Design Support library. And I have report it to android bug source tracking. So wait till the bug will fixed. But if you want the temporary solution you can do it. First add your dynamic menu ..
After adding your menu just write below code ..
It's currently hacky solution. But work for me ...
[update 26-06-2015]
As I have reported this bug at Android Bug source Now Bug is marked as a future release, here is the link https://code.google.com/p/android/issues/detail?id=176300
So we can say that the bug is no more exist on future library. So you don't have to use tricky solution. i will also update this answer again when Future version release number is maintion for this bug.
I found easier way to change navigation view ( work with both submenu and menu). You can re-inflate
NavigationView
at runtime with 2 lines of code. In this example, I re-inflatenew_navigation_drawer_items.xml
using public methodinflateMenu
(You can create a menu xml file with your new submenu)You can add and remove item from navigation view by changing the visibility. Get the item at index and setVisible to true to show and false to hide it.
Use this method to add menu and submenu
and call this method where you setup Drawer Content.