但是,如果您想查看最新的资源,可以通过SDK Manager下载.选择 Android MNC的来源.然后导航到yourAndroidSDK/sources/android-MNC/android/support/design/internal/NavigationMenuPresenter.java @Overrideprotected 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(); } }} 结果 I'm trying to add submenu items to NavigationView programmatically . I'm able to add items into menu but not into submenuAdding 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 workMenu menu = mNavigationView.getMenu();SubMenu subMenu = menu.addSubMenu("Sub menu title");subMenu.add(Menu.NONE, Menu.NONE, index, "SubMenu Item1"); 解决方案 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 toyourAndroidSDK/sources/android-MNC/android/support/design/internal/NavigationMenuPresenter.java@Overrideprotected 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 这篇关于如何以编程方式而不是菜单xml将子菜单项添加到NavigationView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
06-04 22:12