Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Submenu to a Menuitem Programmatically - Android

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?

like image 917
dinbrca Avatar asked Nov 30 '13 10:11

dinbrca


People also ask

Which method is used to add submenu in main menu?

To add menu items and submenus to a JMenu , you use the add(JMenuItem) method.

How to load menu through XML?

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.


2 Answers

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;
}
like image 137
Saad_Sabry Avatar answered Sep 21 '22 11:09

Saad_Sabry


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.

like image 21
rattler Avatar answered Sep 21 '22 11:09

rattler