/ / Dodaj podmenu do menu programowo - Android - Android, menu, podmenu

Dodaj podmenu do Menuitem Programowo - Android - android, menu, podmenu

Próbuję programowo dodać podmenu do mojego MenuItem, Jak mogę to zrobić? oto mój kod do tej pory:

    @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 to identyfikator zdefiniowany w pliku zasobów „ids.xml” jako;

<item type="id" name="extra_options" />

pobieranie SubMenu za pomocą getSubMenu () wydaje się być w porządku, ale kiedy próbuję dodać elementy do SubMenu, pojawia się błąd „NullPointerException”

Czy ktoś ma pojęcie o tym, co jest nie tak z kodem?

Odpowiedzi:

7 dla odpowiedzi № 1

Możesz zamienić „menu.add” na „menu.addSubMenu” Myślę, że to ci pomoże

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

2 dla odpowiedzi nr 2

Spróbuj dodać puste menu oznacz do pozycji menu. Lubię to:

<item
android:id="@+id/menu_common_object"
android:title="@string/menu_common_object">
<menu></menu>
</item>

Po tym

menuItem.getSubMenu().add(..)

będzie działać dobrze w czasie wykonywania.