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

时光总嘲笑我的痴心妄想 提交于 2019-11-30 20:55:40

问题


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?


回答1:


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.




回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!