7

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?

Daniel Nugent
  • 43,104
  • 15
  • 109
  • 137
dinbrca
  • 1,101
  • 1
  • 14
  • 30
  • please see http://stackoverflow.com/questions/7042958/android-adding-a-submenu-to-a-menuitem-where-is-addsubmenu – zohreh Nov 30 '13 at 10:28

2 Answers2

13

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;
}
Saad_Sabry
  • 131
  • 1
  • 4
  • 3
    This could be simplified: SubMenu themeMenu = menu.addSubMenu(Menu.NONE, R.id.extra_options, Menu.NONE,"Menu1"); – mtotschnig Nov 06 '20 at 11:30
  • That simplified version worked for me. But findItem() returned null in the sample provided in the answer. – quilkin Dec 31 '20 at 13:48
6

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.

rattler
  • 379
  • 2
  • 5
  • 15