应该";android:onOptionsItemSelected";返回真或假
在OnOptions ItemSelected中。。。我在开关块中看到了一些不同的代码 案例1(正常可见) 案例2(不确定为什么这样设置) 我的问题应该";android:onOptionsItemSelected";返回真或假,android,Android,在OnOptions ItemSelected中。。。我在开关块中看到了一些不同的代码 案例1(正常可见) 案例2(不确定为什么这样设置) 我的问题 public boolean onOptionsItemSelected (MenueItem item) switch (item.getItemId()){ case R.id.item1: startActivity (new Intent (this, PrefsActivi
public boolean onOptionsItemSelected (MenueItem item)
switch (item.getItemId()){
case R.id.item1:
startActivity (new Intent (this, PrefsActivity.class));
break;
}
return true
案例1和案例2之间有什么区别?请参阅 返回 布尔值返回false以允许正常值 要继续进行的菜单处理,符合 在这里消费 如果返回true,则单击事件将被onOptionsItemSelect()调用使用,并且不会落入其他项单击函数。如果返回false,它可能会在其他项目选择函数中检查事件的ID
您的方法仍然有效,但可能会导致对其他函数的不必要调用。ID最终会通过这些函数,因为没有开关来捕捉它,但返回false更正确。方法的问题是,即使switch语句没有找到项,也会返回true。如果您像对每个开关案例使用另一种方法一样立即返回true,那么您可以假设,如果您在该方法的末尾,则未找到任何开关案例,因此返回false以表明它未被处理。我刚刚遇到了一个问题,我的
getActionBar().setDisplayHomeAsUpEnabled(true);
他没有工作。当触摸后退按钮时,它将高亮显示,但什么也没有发生
我花了一段时间才明白这是真的回归
在我看来,减少代码重复的最佳解决方案是:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_NEW_GAME:
newGame();
break;
default:
return false;
}
return true;
}
根据true-->此处消耗的事件,现在不应转发给其他事件
false-->转发其他事件以消耗 当我们处理多个片段,并且每个片段都有自己的选项菜单和覆盖OnOptionItemSelected(主要在tablet设计中)时,这种布尔返回类型实际上会受益匪浅 在本例中,android跟踪每个片段的OnOptionItemSelected()方法,以避免出现这种情况 a) 如果任何片段正在使用onOptionsItemSelected()中的事件,则返回“true”(停止),否则返回“false”
b) 如果我们返回false,那么它将跟踪其他连接片段的onOptionsItemSelected()
方法,直到它结束所有片段或有人使用它 这里我试着从图表中解释
绿色边界为片段-1,红色边界为片段-2
两个片段都有自己的选项菜单,我已经突出显示了它
现在如果我们单击任意一个OptionmenuItem,它将检查两个片段中onoptionItemSelected()的实现
如果任何片段正在使用事件onOptionsItemSelected返回true,那么它将永远不会尝试其他片段,我们可以减少Android操作系统的开销 当我使用Android Studio生成一个通用应用程序时,onoptionItemSelected()的模板代码会返回true(如果项被消费),否则它会将调用传递到超类
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_mymenuaction) {
return true;
}
return super.onOptionsItemSelected(item);
}
我同意这个概念,但是你应该避免多次返回语句。它降低了可读性。最好传递“结果”布尔字段,并仅在末尾退出。。。一个入口/一个出口。super.onOptionsItemSelected(item)返回的默认值是多少?
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_mymenuaction) {
return true;
}
return super.onOptionsItemSelected(item);
}