安卓:onCreateOptionsMenu()项行动行动、onCreateOptionsMenu

由网友(王的领悟)分享简介:对不起,这是一个愚蠢的问题,但现在的答案是逃避我。我不得不通过Sorry this is a dumb question but the answer is escaping me right now. I have a menu created through@Overridepublic boolean onCr...

对不起,这是一个愚蠢的问题,但现在的答案是逃避我。我不得不通过

Sorry this is a dumb question but the answer is escaping me right now. I have a menu created through

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    menu.add("Email");

    return super.onCreateOptionsMenu(menu);
  }

但我不记得如何时,其选择的,我可以运行我的电子邮件功能设置onclicklistener左右。感谢:)

But I can't remember how to set a onclicklistener so when its selected I can run my email function. Thanks :)

推荐答案

覆盖 onOptionsItemSelected(菜单项项目)。因此,它会像

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case 0:
            // do whatever
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

编辑:

由于这已经得到了这么多点,我应该注意它的是的很好的ID添加到菜单选项。以确保他们始终是唯一的一个好方法是在被放在 RES /值文件夹中。

Since this has gotten so many points, I should note that it is very good to add ID's to the menu options. A good way to ensure they are always unique is to define them in an ids.xml resource that is put in the res/values folder.

ids.xml

<resources>
    <item name="menu_action1" type="id"/>
    <item name="menu_action2" type="id"/>
    <item name="menu_action3" type="id"/>
</resources>

然后,当你重写 onCreateOptionsMenu(菜单菜单)方法,你可以使用的ID像这样:

Then when you override the onCreateOptionsMenu(Menu menu) method, you can use the IDs like so:

@Override
public boolean onCreateOptionsMenu(Menu menu) {

  menu.add(Menu.NONE, R.id.menu_action1, Menu.NONE, R.string.menu_action1);
  menu.add(Menu.NONE, R.id.menu_action2, Menu.NONE, R.string.menu_action1);

  return super.onCreateOptionsMenu(menu);
}

覆盖 onOptionsItemSelected(菜单项项目)

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.menu_action1:
            // do whatever
            return true;
        case R.id.menu_action2:
            // do whatever
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

您这样做的原因是活动将与菜单选项覆盖这一点,但片段也可以添加自己的自己的菜单项。使用 ids.xml 确保ID是唯一的无论哪个顺序排列放置。

The reason you do this is the Activity would override this with menu options, but Fragments can also add their own menu items. Using the ids.xml ensures the IDs are unique no matter which order they are placed.