快速鍵
為了提高對選項菜單的操作速度,你可以在具有物理按鍵的裝置上為菜單增加快速鍵.快速鍵可以對應鍵盤上的字母或數字.你需要做的是為<item>
元素指定屬性android:alphabeticShortcut
和android:numericShortcut
的值.你也可以在代碼中使用方法setAlphabeticShortcut(char)
和setNumericShortcut(char)
.來完成.快速鍵並不是大小寫敏感的.
例如,如果你把"s"鍵作為功能表項目 "save" 的快速鍵,那麼當菜單開啟時,使用者按下了 "s" 鍵,"save"功能表項目就被選擇.
快速鍵會以tip的方式出現在功能表項目的名字的下方(除非菜單是表徵圖菜單,它只能在使用者按下"菜單"鍵時出現).
注:快速鍵只能在有物理鍵盤的裝置上起作用,並且不能用在操作功能表上.
動態添加菜單intents
有時你可能希望通過一個功能表項目使用Intent啟動一個activiry(不論這個activity在你自己的程式中還是在另一個程式中 ).如果你知道了需要的Intent,你可以在響應對應功能表項目的回調方法中執行Intent的startActivity()
方法完成.
然而,如果你不能確信使用者裝置上具有響應這個intent的程式,那麼添加的功能表項目可能成多餘的.為瞭解決這個問題,Android 允許你在發現具有所有響應目標intent的activity時動態添加功能表項目.
要跟據是否具有響應目標intent的Activity來添加功能表項目,你需要:
- 定義一個具有類別
CATEGORY_ALTERNATIVE
和/或CATEGORY_SELECTED_ALTERNATIVE
的intent,當然還可以跟據需要添加其它類別.
- 調用
Menu.addIntentOptions()
.
Android會尋找可以執行這個的程式然後把它添加到你的菜單上.
如此一來,如果沒有滿之intent的程式存在,則沒有功能表項目會添加.
注:CATEGORY_SELECTED_ALTERNATIVE
被用於處理螢幕上當前被選擇的元素.所以,它只能用於在onCreateContextMenu()中被建的菜單.
例如:
@Override<br />public boolean onCreateOptionsMenu(Menu menu){<br /> super.onCreateOptionsMenu(menu);</p><p> // Create an Intent that describes the requirements to fulfill, to be included<br /> // in our menu. The offering app must include a category value of Intent.CATEGORY_ALTERNATIVE.<br /> Intent intent = new Intent(null, dataUri);<br /> intent.addCategory(Intent.CATEGORY_ALTERNATIVE);</p><p> // Search and populate the menu with acceptable offering applications.<br /> menu.addIntentOptions(<br /> R.id.intent_group, // Menu group to which new items will be added<br /> 0, // Unique item ID (none)<br /> 0, // Order for the items (none)<br /> this.getComponentName(), // The current activity name<br /> null, // Specific items to place first (none)<br /> intent, // Intent created above that describes our requirements<br /> 0, // Additional flags to control items (none)<br /> null); // Array of MenuItems that correlate to specific items (none)</p><p> return true;<br />}
每發現一個對應這個intent的activity,就會添加一個功能表項目.將intent 過濾器中 android:label
的值作為功能表項目的標題,將程式的表徵圖作為功能表項目的表徵圖. 方法addIntentOptions()
返回被添加的功能表項目的數目.
注:當調用 addIntentOptions()
時,會將參數menu
group所指的group下的所有功能表項目替換掉.
允許你的activity能被添加到其它菜單中
你也可以把你的activity的服務向其它程式提供.於是你的程式可以被其它程式的菜單所包含 (跟上一小節反過來了).
要想能被其它程式的菜單所包含,你需要定義一個intent 過濾器, 但這個過濾器必須在類別中包含 CATEGORY_ALTERNATIVE
和/或CATEGORY_SELECTED_ALTERNATIVE
,例如:
<intent-filter label="Resize Image"><br /> ...<br /> <category android:name="android.intent.category.ALTERNATIVE" /><br /> <category android:name="android.intent.category.SELECTED_ALTERNATIVE" /><br /> ...<br /></intent-filter>