我怎样才能改变在Android上的选项菜单中选择一个菜单项? [英] How can I alter a MenuItem on the Options Menu on Android?
问题描述
我有我的活动
与菜单项
启动的选项菜单。当此菜单项
选择,我想改变菜单,以便它包含了一个菜单项
停止。最后当停止时,我想改变返回到开始。
下面是我的code部位不工作。我有两个开始和停止,在 mymenu.xml
上市我也许应该删除停在创建菜单时:
公共类MyActivity延伸活动{
私人布尔isStarted = FALSE;
@覆盖
公共布尔onCreateOptionsMenu(功能菜单){
MenuInflater充气= getMenuInflater();
menu.removeItem(R.id.stop);
inflater.inflate(R.menu.mymenu,菜单);
返回true;
}
@覆盖
公共布尔onOptionsItemSelected(菜单项项){
开关(item.getItemId()){
案例R.id.start:
isStarted = TRUE;
返回true;
案例R.id.stop:
isStarted = FALSE;
返回true;
默认:
返回super.onOptionsItemSelected(项目);
}
}
@覆盖
公共布尔prepareOptionsMenu(功能菜单)在{
如果(isStarted){
menu.removeItem(R.id.start);
menu.add(R.id.stop);
} 其他 {
menu.removeItem(R.id.stop);
menu.add(R.id.start);
}
返回true;
}
}
对于这种类型的操作,我通常选择不改变菜单项,只是隐藏那些你不需要
@覆盖
公共布尔prepareOptionsMenu(功能菜单)在{
super.on prepareOptionsMenu(菜单);
menu.findItem(R.id.start).setVisible(isStarted!);
menu.findItem(R.id.stop).setVisible(isStarted);
返回true;
}
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;
}
}
For this type of operation I usually choose not to alter the menu items, but just hide the ones you don't need:
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
menu.findItem(R.id.start).setVisible(!isStarted);
menu.findItem(R.id.stop).setVisible(isStarted);
return true;
}
这篇关于我怎样才能改变在Android上的选项菜单中选择一个菜单项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!