英文原文:http://developer.android.com/guide/topics/ui/menus.html#intents
基于Intent添加菜单项
有时候你想通过菜单项来启动一个能够处理特定intent的activity(无论该activity是否在当前应用程序中或其他应用程序中).当你确定想使用的intent的详情以及确定用来启动该intent的菜单项时,显然你可以通过在菜单项被选中回调函数中(比如onOptionsItemSelected()
)执行StartActivity(intent)方法。
然而,如果你不确定本机中是否包含能够处理该intent的应用程序(译者注:有时候也没办法确定)。添加一个用来发送该intent的菜单项可能导致的结果是:等效于添加一个无效的菜单项。因为有可能没有activity能够处理该intent。为了解决这个问题,android 系统以如下方式进行处理:只有在本机找到能够处理该intent的activity时,才动态的将该activity作为菜单项添加到菜单。
将能够接受该intent的activity以菜单项方式添加到菜单的步骤如下:
1 定义一个intent且将其catagary属性设为CATEGORY_ALTERNATIVE
和/或CATEGORY_SELECTED_ALTERNATIVE
,然后再添加其它任何你想要的要求.
2调用Menu.addIntentOptions()
方法,android系统会自动找出所有能够处理该intent的activity并把他们添加到菜单中。
如果本机没有能够处理该intent的activity,则没有菜单项被添加.
警告:因为CATEGORY_SELECTED_ALTERNATIVE已经被用来处理当前被选择的条目,所以,这个类型属性只能用在onCreateContextMenu()方法中。
添加动态菜单例子:
@Override
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
// Create an Intent that describes the requirements to fulfill, to be included
// in our menu. The offering app must include a category value of Intent.CATEGORY_ALTERNATIVE.
Intent intent = new Intent(null, dataUri);
intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
// Search and populate the menu with acceptable offering applications.
menu.addIntentOptions(
R.id.intent_group, // Menu group to which new items will be added 组id
0, // Unique item ID (none) 菜单项id
0, // Order for the items (none)
this.getComponentName(), // The current activity name
null, // Specific items to place first (none)
intent, // Intent created above that describes our requirements
0, // Additional flags to control items (none)
null); // Array of MenuItems that correlate to specific items (none)
return true;
}
android系统为找到的能够处理该intent的每个activity添加一个菜单项到菜单,使用intent-filter的android:label
属性作为菜单项的标题,使用activity所属应用程序的icon作为菜单项的icon. addIntentOptions()
方法返回添加的菜单项数目。
警告:当你调用addIntentOptions()方法时,它会覆盖所有的由第一个参数指定的组中的菜单项.
允许你的activity被添加的其它应用程序的的菜单中
为了让你的activity添加到其它应用程序的菜单中,你必须像平常一样定义一个intent-filter,但必须确保intent filter 的category属性包含CATEGORY_ALTERNATIVE
和/或CATEGORY_SELECTED_ALTERNATIVE
<intent-filter label="@string/resize_image">
...
<category android:name="android.intent.category.ALTERNATIVE" />
<category android:name="android.intent.category.SELECTED_ALTERNATIVE" />
...
</intent-filter>
想参考使用动态菜单的demo程序,请参考 NotePad示例代码.