我有这个布局:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- The ActionBar -->
<include
layout="@layout/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<!-- The main content view -->
<FrameLayout
android:id="@+id/flContent"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<!-- The navigation drawer -->
<android.support.design.widget.NavigationView
android:id="@+id/nvView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="@android:color/white"
app:menu="@menu/drawer_menu"
app:headerLayout="@layout/nav_header"/>
所以,在查看NavigationView
时,我们有一个属性:
app:menu="@menu/drawer_menu"
我有一个XML id为menu folder。
我想创建动态菜单,即在代码中创建“MenuItem”对象并将其设置到NavigationView
中。
这样做正确吗? 这是最佳实践吗? 这可行吗?
注意:我的代码使用“静态drawer_menu”,我想改进它。
我在等待。
[编辑]
我已经实现了:
Menu menu = nvDrawer.getMenu();
for (KSMenuItem kmi : menus.values()) {
if (menu.size() == 0) {
menu.add(kmi.getId());
}
if (menu.getItem(kmi.getId()) == null) {
menu.add(kmi.getId());
}
MenuItem mi = menu.getItem(kmi.getId());
mi.setIcon(kmi.getIcon());
mi.setTitle(kmi.getTittle());
}
但是发生了以下错误:
06-27 15:26:15.538 15335-15335/? E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: com.example.sticdev30.newdrawer, PID: 15335 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sticdev30.newdrawer/com.example.sticdev30.newdrawer.MainActivity}: android.content.res.Resources$NotFoundException: String resource ID #0x1
KSMenuItem是我的菜单数据的POJO。在kmi.id中,我通知了增量整数...
我正在等待。