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 contains a MenuItem
"Stop". And finally when "Stop" is selected, I would like to alter back to "Start".
Here is parts of my code that isn't working. I have both "Start" and "Stop" listed in mymenu.xml
I should probably remove "stop" when the menu is created:
public class MyActivity extends Activity {
private boolean isStarted = false;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
menu.removeItem(R.id.stop);
inflater.inflate(R.menu.mymenu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.start:
isStarted = true;
return true;
case R.id.stop:
isStarted = false;
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
if(isStarted) {
menu.removeItem(R.id.start);
menu.add(R.id.stop);
} else {
menu.removeItem(R.id.stop);
menu.add(R.id.start);
}
return true;
}
}
menu.removeItem(R.id.stop);
aftergetMenuInflater();
but it didn't work. I either get two menu items, one "start" and one "false" (should be "stop"), or the menu crashes when I should be shown. – AlgonquinremoveItem()
? InonPrepareOptionsMenu()
? – BoatmanonCreateOptionsMenu()
the first time, then I alter the items inonPrepareOptionsMenu()
. I added this to the code in the question now. – Algonquin