Add Submenu to a Menuitem Programmatically - Android

android, menu, submenu

Solution

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;
}

Problem

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?

Original source

Related problems