How to add submenu items to NavigationView programmatically instead of menu xml

喜欢而已 提交于 2019-12-30 02:17:27

问题


I'm trying to add submenu items to NavigationView programmatically . I'm able to add items into menu but not into submenu

Adding items to menu works

Menu menu = mNavigationView.getMenu();
menu.add(Menu.NONE, Menu.NONE, index, "Menu Item1");

But adding items to sub menu doesn't work

Menu menu = mNavigationView.getMenu();
SubMenu subMenu = menu.addSubMenu("Sub menu title");
subMenu.add(Menu.NONE, Menu.NONE, index, "SubMenu Item1");

回答1:


The trick to call BaseAdapter.notifyDataSetChanged on the underlying Adapter that contains the menu items. You could use reflection to grab the ListView or just loop over the NavigationView children until you reach it.

This isn't the most up-to-date code, as fas as I know Google hasn't pushed the most recent changes to the Support Library, but essentially NavigationMenuPresenter.prepareMenuItems is called when you call BaseAdpater.notifyDataSetChanged.

But if you want to see the most recent source, you can download it through the SDK Manager. Choose Sources for Android MNC. Then navigate to

yourAndroidSDK/sources/android-MNC/android/support/design/internal/NavigationMenuPresenter.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    final Menu menu = mNavigationView.getMenu();
    for (int i = 0; i < 4; i++) {
        menu.add("Menu Item " + (i + 1));
    }
    final SubMenu subMenu = menu.addSubMenu("SubMenu Title");
    for (int i = 0; i < 2; i++) {
        subMenu.add("SubMenu Item " + (i + 1));
    }
    for (int i = 0, count = mNavigationView.getChildCount(); i < count; i++) {
        final View child = mNavigationView.getChildAt(i);
        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();
        }
    }

}

Results




回答2:


Somebody figured out a way to do it via reflection and accessing a private field. It's not pretty, but it'll work, for the moment. https://stackoverflow.com/a/30604299/4232051



来源:https://stackoverflow.com/questions/30609408/how-to-add-submenu-items-to-navigationview-programmatically-instead-of-menu-xml

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