I have an Options Menu on my Activity
with an MenuItem
\"Start\". When this MenuItem
is selected I would like to alter the Menu so it
I got the solution. You are basically deleting the MenuItem
when calling removeItem()
thus also deleting the reference. Using this code works.
private boolean isStarted = false;
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 1:
isStarted = true;
return true;
case 0:
isStarted = false;
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
if(isStarted) {
menu.removeItem(1);
menu.add(0, 0, 0, "Stop");
} else {
menu.removeItem(0);
menu.add(0, 1, 0, "Start");
}
return super.onPrepareOptionsMenu(menu);
}
You have to create the MenuItem
again. Thats also the reason for the false
label. Actually you don't need the MenuInflater
as you create the Menu
via code so also no need for any menu XML file.