如若"安卓onOptionsItemSelected"返回true或falseonOptionsItemSelected、QUOT、false、true

2023-09-04 08:24:52 作者:挽歌

在onOptionsItemSelected ......我看到一些code是在开关块不同。

In onOptionsItemSelected... I saw some code that are different in the switch block.

案例1(通常看到的)

public boolean onOptionsItemSelected (MenueItem item)
       switch (item.getItemId()){
             case R.id.item1:
             startActivity (new Intent (this, PrefsActivity.class));
             break;
       }
       return true

案例2(不确定为什么它的这种方式设置)

public boolean onOptionsItemSelected(MenuItem item) {
       switch (item.getItemId()) {
               case MENU_NEW_GAME:
               newGame();
               return true;
       }
       return false;

我的提问

什么是案例1和第2种情况之间的差异?

What are the differences between Case 1 and Case 2?

推荐答案

kleaver,

每对文件onOptionsItemSelected()

返回

,则返回false,以允许正常   菜单的处理进行,真到   在这里消费。

boolean Return false to allow normal menu processing to proceed, true to consume it here.

的,如果返回true的单击事件将由onOptionsItemSelect()调用消耗,不会落空其他项目点击功能。如果你的回报假时,可以检查其他项目选择功能,事件的ID。

The if returned true the click event will be consumed by the onOptionsItemSelect() call and won't fall through to other item click functions. If your return false it may check the ID of the event in other item selection functions.

您的方法仍然可以工作,但可能会导致不必要的调用等功能。该ID将通过这些功能最终下跌,因为没有开关赶上它,但返回false是比较正确的。

Your method will still work, but may result in unnecessary calls to other functions. The ID will ultimately fall through those functions since there is no switch to catch it, but return false is more correct.