您可以使用應用程式列新增使用者動作按鈕。這項功能可讓您將目前情境中最關鍵的動作置於應用程式頂端。舉例來說,當使用者查看相片膠卷時,相片瀏覽應用程式可能會在頂端顯示「分享」和「建立相簿」按鈕。當使用者查看個別相片時,應用程式可能會顯示「裁剪」和「濾鏡」按鈕。
應用程式列的空間有限。如果應用程式宣告的動作多於應用程式列可容納的數量,應用程式列會將多餘的動作傳送至「溢位」選單。應用程式也可以指定動作一律顯示在溢位選單中,而非顯示在應用程式列中。
![這張圖片顯示 Now in Android 應用程式,其中含有動作列圖示](https://developer.android.google.cn/static/images/ui/notifications/actions_actionbar.png?hl=zh-tw)
新增動作按鈕
所有動作按鈕和動作溢位中可用的其他項目,都是在 XML 選單資源中定義。如要將動作新增至動作列,請在專案的 res/menu/
目錄中建立新的 XML 檔案。
針對要納入動作列的每個項目新增 <item>
元素,如以下選單 XML 範例檔案所示:
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <!-- "Mark Favorite", must appear as action button if possible. --> <item android:id="@+id/action_favorite" android:icon="@drawable/ic_favorite_black_48dp" android:title="@string/action_favorite" app:showAsAction="ifRoom"/> <!-- Settings, must always be in the overflow. --> <item android:id="@+id/action_settings" android:title="@string/action_settings" app:showAsAction="never"/> </menu>
app:showAsAction
屬性可指定動作是否會顯示為應用程式列上的按鈕。如果您設定 app:showAsAction="ifRoom"
(如同範例程式碼的「favorite」 動作),如果應用程式列有足夠空間,動作就會顯示為按鈕。如果沒有足夠的空間,系統會將多餘的動作傳送至溢位選單。如果您設定 app:showAsAction="never"
(如範例程式碼的「設定」動作),該動作一律會列在溢位選單中,不會顯示在應用程式列中。
如果動作顯示在應用程式列中,系統會使用動作的圖示做為動作按鈕。您可以在 Material Icons 中找到許多實用的圖示。
回應動作
當使用者選取其中一個應用程式列項目時,系統會呼叫活動的 onOptionsItemSelected()
回呼方法,並傳遞 MenuItem
物件,指出使用者輕觸哪個項目。在 onOptionsItemSelected()
的實作中,請呼叫 MenuItem.getItemId()
方法,判斷使用者輕觸的是哪個項目。傳回的 ID 會與您在相應 <item>
元素的 android:id
屬性中宣告的值相符。
例如,下列程式碼片段會檢查使用者選取的動作。如果方法無法辨識使用者的動作,就會叫用超類別方法:
Kotlin
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { R.id.action_settings -> { // User chooses the "Settings" item. Show the app settings UI. true } R.id.action_favorite -> { // User chooses the "Favorite" action. Mark the current item as a // favorite. true } else -> { // The user's action isn't recognized. // Invoke the superclass to handle it. super.onOptionsItemSelected(item) } }
Java
@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_settings: // User chooses the "Settings" item. Show the app settings UI. return true; case R.id.action_favorite: // User chooses the "Favorite" action. Mark the current item as a // favorite. return true; default: // The user's action isn't recognized. // Invoke the superclass to handle it. return super.onOptionsItemSelected(item); } }