I am trying to add a SubMenu to my MenuItem programmatically, How do I do that? here's my code so far:
@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);
}
R.id.extra_options is an ID defined at "ids.xml" resource file as;
<item type="id" name="extra_options" />
getting the SubMenu with the getSubMenu() seems to be fine but when I try to add Items to the SubMenu I get an error "NullPointerException"
Anyone got an idea of what is wrong with the code?
To add menu items and submenus to a JMenu , you use the add(JMenuItem) method.
Defining a Menu in XML. For all menu types, Android provides a standard XML format to define menu items. Instead of building a menu in your activity's code, you should define a menu and all its items in an XML menu resource. You can then inflate the menu resource (load it as a Menu object) in your activity or fragment.
You can replace "menu.add" to be "menu.addSubMenu" I think this will help you
@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;
}
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>
After this
menuItem.getSubMenu().add(..)
will work fine at runtime.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With