英文原文:http://developer.android.com/guide/topics/ui/menus.html?#intents
根據傳入Intent對象添加Menu組件
在一些情況下,你需要通過菜單組件,使用intent來啟動一個activity(無論這個activity在否當前應用中)。當你知道這個你使用的intent的詳情和準備好一個菜單組件來啟動這個intent的時候,你可以在這個組件所對應的選擇回呼函數(例如onOptionsItemSelected() )中執行以這個intent為參數的startActivity()方法。
但是,當本機內沒有一個應用程式能夠處理這個intent,你建立的這個發送這個intent的菜單控制項會最終無效,因為沒有一個activity能夠與這個intent對應。為瞭解決這個問題,Android系統提供了下面一種機制,使得只有在Android能夠在本地找到能夠處理這個intent的activity時候,才動態地添加這個菜單組件。
添加動態菜單組件的步驟如下:
1、定義一個種類為CATEGORY_ALTERNATIVE 或者CATEGORY_SELECTED_ALTERNATIVE和其他需要使用的屬性的intent對象
2、調用 Menu.addIntentOptions(),Android系統會首先在本地尋找能夠處理這個intent的activity,如果能夠找到則Android系統自動添加這個組件到菜單中,否則不添加。
注意:因為CATEGORY_SELECTED_ALTERNATIVE 是用來已經在介面中選擇條目的intent的。所以,這個類型屬性只能用在onCreateContextMenu()方法中。
例如:
@Override
publicboolean onCreateOptionsMenu(Menu
menu){
super.onCreateOptionsMenu(menu);
// Createan Intent that describes the requirements to fulfill, to be included
// in ourmenu. The offering app must include a category value ofIntent.CATEGORY_ALTERNATIVE.
Intent intent=newIntent(null,
dataUri);
intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
// Searchand populate the menu with acceptable offering applications.
menu.addIntentOptions(
R.id.intent_group, //
Menugroup to which new items will be added
0, // Uniqueitem ID (none)
0, // Orderfor the items (none)
this.getComponentName(), //
Thecurrent activity name
null, // Specificitems to place first (none)
intent,// Intent created above thatdescribes our requirements
0, //Additional flags to control items (none)
null); // Array ofMenuItems that correlate to specific
items (none)
returntrue;
}
對於每一個android系統中找到的符合要求的activity,都會一個與之對應的菜單組件建立,並且使用這個activity中能夠對應得上這個intent的intent
filter的android:label作為這個菜單組件的標題和這個activity的應用程式的表徵圖作為表徵圖。addIntentOptions()將成功建立的菜單組件總數作為傳回值。
Note: When you call addIntentOptions(),
it overrides any and all menu items by themenu group specified in the first argument.
讓你的activity能夠添加到其他應用程式的菜單中
為了達到標題中的目的,你的activity必須要在intent filter中的類型屬性使用下面的兩個值之一:CATEGORY_ALTERNATIVE 或者 CATEGORY_SELECTED_ALTERNATIVE 。
例子:
<intent-filterlabel="@string/resize_image">
...
<categoryandroid:name="android.intent.category.ALTERNATIVE"/>
<categoryandroid:name="android.intent.category.SELECTED_ALTERNATIVE"/>
...
</intent-filter>