第一个选项
你必须覆盖onOptionsItemSelected
活动中的方法,当用户单击“选项”菜单中的项目时调用该方法。在该方法中,您可以检查单击了哪些项目。
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menu_item1:
Intent intent = new Intent(this, ActivityForItemOne.class);
this.startActivity(intent);
break;
case R.id.menu_item2:
// another startActivity, this is for item with id "menu_item2"
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
还有onContextItemSelected
方法的工作原理类似,但对于上下文菜单(我不确定,你的意思是什么菜单)。
更多信息请访问http://developer.android.com/guide/topics/ui/menus.html http://developer.android.com/guide/topics/ui/menus.html
EDIT:
第二个选项
我认为第一个选项更容易,但是从您的代码中我看到,您希望将活动作为一个操作来启动(因为String
参数输入Intent
构造函数)。为此,您需要在 AndroidManifest.xml 中指定一个操作。所以,如果我开始活动ActivityForItemOne
(来自前面的示例)<application>
AndroidManifest.xml 中的元素如下所示:
<application ...>
...
<activity android:label="Activity For First Item" android:name=".ActivityForItemOne">
<intent-filter>
<action android:name="my.app.ITEMONE" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
And the Intent
将:
Intent intent = new Intent("my.app.ITEMONE");
The my.app.
是您的应用程序的包。不一定要使用您的应用程序包,但为了操作的唯一性,建议您使用它。
更多信息请访问:
类意图 - 操作和类别常量 http://developer.android.com/reference/android/content/Intent.html
动作元素 http://developer.android.com/guide/topics/manifest/action-element.html
意图和意图过滤器 http://developer.android.com/guide/topics/intents/intents-filters.html
希望这能解决您的问题。