Android:onCreateOptionsMenu() 项目操作 [英] Android: onCreateOptionsMenu() item action

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

问题描述

我通过以下方式创建了一个菜单:

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.

推荐答案

覆盖 onOptionsItemSelected(MenuItem item).所以它会像

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

既然这已经获得了很多分数,我应该指出,将 ID 添加到菜单选项中是非常好的.确保它们始终唯一的一个好方法是在位于 res/values 文件夹中的 ids.xml 资源中定义它们.

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(Menu menu) 方法时,您可以像这样使用 ID:

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

@Override
public boolean onCreateOptionsMenu(Menu menu) {
  super.onCreateOptionsMenu(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 true;
}

覆盖 onOptionsItemSelected(MenuItem item).

@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);
    }
}

你这样做的原因是 Activity 会用菜单选项覆盖它,但 Fragments 也可以添加它们自己的菜单项.使用 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.

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

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