How to add MenuItem to SubMenu in Google's new NavigationView?

702 views Asked by At

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?

2

There are 2 answers

1
Moinkhan On

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 .. ");
0
Jose Calles On

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.