I have made an xml for my drawer menu which contains the following MenuItem:
<item android:title="Contacts"
android:id="@+id/contact_list">
<menu>
</menu>
</item>
In my MainActivity I get a reference to the empty SubMenu and try to add a new test MenuItem to the the SubMenu.
mNavMenu = mNavigationView.getMenu();
mNavMenu.findItem(R.id.contact_list).getSubMenu().add("hello");
Unfortunately, this is not working and the MenuItems are not being added. I have tried many other different variations of this but none of them update the SubMenu in my navigation drawer.
Could this possibly be a bug?
So apparently, the only solution right now is to use reflection to call notifyDataSetChanged() on the menu:
for (int j = 0, count = mNavigationView.getChildCount(); j < count; j++) {
final View child = mNavigationView.getChildAt(j);
if (child != null && child instanceof ListView) {
final ListView menuView = (ListView) child;
final HeaderViewListAdapter adapter = (HeaderViewListAdapter) menuView.getAdapter();
final BaseAdapter wrapped = (BaseAdapter) adapter.getWrappedAdapter();
wrapped.notifyDataSetChanged();
}
}
This will update the menu with your new items.
You are doing it in wrong way... You don't have to find the menu agian ... just call the method on the instance of mNavMenu ..
mNavMenu = mNavigationView.getMenu();
mNavMenu.addSubMenu("It's new bro .. ");
来源:https://stackoverflow.com/questions/30690228/how-to-add-menuitem-to-submenu-in-googles-new-navigationview