安卓:onCreateOptionsMenu()项行动 [英] Android: onCreateOptionsMenu() item action

查看:166
本文介绍了安卓:onCreateOptionsMenu()项行动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 /值 ids.xml 资源来定义它们$ C>文件夹中。

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.

这篇关于安卓:onCreateOptionsMenu()项行动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆