我正在尝试将新菜单项添加到新 Material Design 抽屉面板中的子菜单。
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
...
<android.support.design.widget.NavigationView
android:id="@+id/main_navigation"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/channel_list_header"
app:menu="@menu/menu_nav" />
</android.support.v4.widget.DrawerLayout>
我确实有 @menu/menu_nav 设置,但现在想添加新的菜单项:
NavigationView mDrawerList = (NavigationView) findViewById(R.id.main_navigation);
Menu menu = mDrawerList.getMenu();
Menu topChannelMenu = menu.addSubMenu("Top Channels");
topChannelMenu.add("Foo");
topChannelMenu.add("Bar");
topChannelMenu.add("Baz");
mDrawerList.invalidate(); // Trying to force a redraw, doesn't help.
@menu/menu_nav 文件中的菜单项会显示,但不会显示新添加的菜单项。 任何想法如何做到这一点?
最佳答案
[2016 年 3 月 20 日更新] 错误已解决。所以不用担心。
[以下内容已过时。]
向 NavigationView 添加动态菜单目前是设计支持库中的错误。 我已将其报告给 android 错误源跟踪。所以等到bug修复。但是,如果您想要 临时解决方案,您可以这样做。首先添加您的动态菜单..
navView = (NavigationView) findViewById(R.id.navView);
Menu m = navView.getMenu();
SubMenu topChannelMenu = m.addSubMenu("Top Channels");
topChannelMenu.add("Foo");
topChannelMenu.add("Bar");
topChannelMenu.add("Baz");
添加菜单后,只需编写以下代码..
MenuItem mi = m.getItem(m.size()-1);
mi.setTitle(mi.getTitle());
这是目前的 hacky 解决方案。但是为我工作...
[2015 年 6 月 26 日更新]
正如我在 Android 错误源中报告的这个错误现在错误被标记为 future 版本,这里是链接 https://code.google.com/p/android/issues/detail?id=176300
所以我们可以说这个错误在未来的库中不再存在。所以你不必使用棘手的解决方案。当此错误的 future 版本版本号被维护时,我还将再次更新此答案。
关于android - 如何以编程方式将子菜单项添加到新的 Material 设计 android 支持库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30695038/