我有一个带有“开始”的选项Activity
菜单MenuItem
。选择此MenuItem
选项后,我想更改菜单,使其包含MenuItem
“停止”。And finally when "Stop" is selected, I would like to alter back to "Start".
这是我的部分代码不起作用。我列出了“开始”和“停止”,mymenu.xml
我应该在创建菜单时删除“停止”:
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;
}
}