din*_*rca 3 android menu submenu
我试图以编程方式将一个SubMenu添加到我的MenuItem,我该怎么做?到目前为止这是我的代码:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(Menu.NONE, R.id.extra_options, Menu.NONE, "Menu1")
.setIcon(Config.chooseActionBarIcon(
MainActivity.this, "ic_actionbar_font"))
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
SubMenu themeMenu = menu.findItem(R.id.extra_options).getSubMenu();
themeMenu.clear();
themeMenu.add(0, R.id.theme_auto, Menu.NONE, "Automatic");
themeMenu.add(0, R.id.theme_day, Menu.NONE, "Default");
themeMenu.add(0, R.id.theme_night, Menu.NONE, "Night");
themeMenu.add(0, R.id.theme_batsave, Menu.NONE, "Battery Saving");
return super.onCreateOptionsMenu(menu);
}
Run Code Online (Sandbox Code Playgroud)
R.id.extra_options是在"ids.xml"资源文件中定义的ID;
<item type="id" name="extra_options" />
Run Code Online (Sandbox Code Playgroud)
使用getSubMenu()获取SubMenu似乎没问题,但是当我尝试将项添加到SubMenu时,我收到错误"NullPointerException"
任何人都知道代码有什么问题?
小智 8
您可以将"menu.add"替换为"menu.addSubMenu"我认为这会对您有所帮助
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.single_product, menu);
menu.addSubMenu(Menu.NONE, R.id.extra_options, Menu.NONE,"Menu1");
SubMenu themeMenu = menu.findItem(R.id.extra_options).getSubMenu();
themeMenu.clear();
themeMenu.add(0, R.id.theme_auto, Menu.NONE, "Automatic");
themeMenu.add(0, R.id.theme_day, Menu.NONE, "Default");
themeMenu.add(0, R.id.theme_night, Menu.NONE, "Night");
themeMenu.add(0, R.id.theme_batsave, Menu.NONE, "Battery Saving");
return true;
}
Run Code Online (Sandbox Code Playgroud)
Try adding empty menu tag into your menu item. Like this:
<item
android:id="@+id/menu_common_object"
android:title="@string/menu_common_object">
<menu></menu>
</item>
Run Code Online (Sandbox Code Playgroud)
After this
menuItem.getSubMenu().add(..)
Run Code Online (Sandbox Code Playgroud)
will work fine at runtime.