英文原文: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示例代碼.