我的应用程序遇到了另一个问题。当猫死了,我点击了“结果屏幕”(这不是一个新活动,但我隐藏了所有当前元素,并显示一个新的文本视图,表明死亡原因),我想隐藏菜单项,但对于一些原因是它没有回复isHeDead()
。
基本上问题似乎是它在onCreateOptionsMenu
内没有看到“return false”,因为由于某种原因,isHeDead()
在那里不起作用,即使该方法适用于其他任何地方。
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(fab_menu, menu);
while (!isHeDead()){
return true;
}
return false;
}
public Boolean isHeDead() {
TextView t = (TextView) findViewById(R.id.textDiedOf);
TextView textName = (TextView) findViewById(R.id.CatsTitleStats);
TextView textAge = (TextView) findViewById(R.id.CatsAgeStat);
TextView textStats1 = (TextView) findViewById(R.id.CatsStats);
TextView textStats2 = (TextView) findViewById(R.id.CatsStats2);
ImageView image = (ImageView) findViewById(R.id.imageViewCat);
if (cat.getAge() >= 20) {
textName.setVisibility(View.GONE);
textAge.setVisibility(View.GONE);
textStats1.setVisibility(View.GONE);
textStats2.setVisibility(View.GONE);
image.setVisibility(View.GONE);
t.setText("Sorry! " + getIntent().getStringExtra(KEY_NAME_EXTRA) + " died of old age.");
return true;
} else if (cat.getAnger() >= 10) {
textName.setVisibility(GONE);
textAge.setVisibility(View.GONE);
textStats1.setVisibility(View.GONE);
textStats2.setVisibility(View.GONE);
image.setVisibility(View.GONE);
t.setText("Sorry! " + getIntent().getStringExtra(KEY_NAME_EXTRA) + " died of madness.");
return true;
} ///etc...
}
用户选项(不确定这是否与菜单问题有关,但仍然存在)。
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
/// FEED ///
case R.id.action_feed:
int qualityRandom = (int) (Math.random() * 10);
if (qualityRandom == 5) {
cat.happy(-2);
cat.healthy(-30);
cat.angry(2);
cat.thirsty(2);
ageStat();
Stats1();
Stats2();
if (isHeDead()) {
break;
} else {
Toast.makeText(CatStatus.this, "Food was in a poor state...", Toast.LENGTH_SHORT).show();
break;
}
} else {
cat.happy(1);
cat.healthy(10);
cat.hungry(-3);
cat.angry(-1);
ageStat();
Stats1();
Stats2();
Toast.makeText(CatStatus.this, "Yummy!", Toast.LENGTH_SHORT).show();
break;
}
/// DRINK ///
case R.id.action_drink: ///etc...
答案 0 :(得分:0)
当您点击结果屏幕时,如果您没有参加新活动,则不会调用onCreateOptionsMenu!
您需要保留对菜单的引用:
private Menu myMenu;
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(fab_menu, menu);
this.myMenu = menu;
while (!isHeDead()){
return true;
}
return false;
}
然后,你可以在你的isHeDead()方法中调用:
menu.setGroupVisible(R.id.main_menu_group, false);
或:
menu.clear();
这取决于你想要什么。
检查这个答案:
Hide/Show Action Bar Option Menu Item for different fragments
答案 1 :(得分:0)
onCreateOptionsMenu仅在应用启动活动
时被调用一次