天天看點

譯--ToolBar(二)增加Handing Actions

增加Handing Actions

app bar 允許使用者自己增加action,可以把比較重要的action放在app bar的右邊,例如,一個相冊應用可以在app bar上增加分享和建立相簿的

action,這樣使用者在浏覽照片的時候就可以直接點選app bar上的按鈕來對照片進行操作。

app bar的空間是有限的,如果定義的action超過了app bar可以容納的最大數,這些action就會被放入overflow menu中,當然,action也可以

被設定為隻在overflow中顯示。

譯--ToolBar(二)增加Handing Actions

樣例1.帶有一個action和一個overflow的toolbar。

增加Action Buttons

不論是在app bar上直接顯示的,還是在overflow中的action button都是在menu resource中定義的,想要建立一個action,

首先要在res/menu/目錄下建立一個xml檔案。

下面是一個xml例子:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <!-- "Mark Favorite", should 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, should always be in the overflow -->
    <item android:id="@+id/action_settings"
          android:title="@string/action_settings"
          app:showAsAction="never"/>

</menu>
           

app:showAsAction

屬性定義了action在app bar上的顯示方式,如果設定為

app:showAsAction="ifRoom"

,就代表如果app bar上面有空間,

就進行顯示,如果沒有空間,就放在overflow中顯示(預設在overflow中隻顯示title);如果設定為

app:showAsAction="never"

就表示此action将總是顯示在overflow中。

系統使用action icon作為action button顯示在app bar上,你可以在Material Icons

找到很多有用的icons.

對Actions做出響應

當使用者點選app bar上的一個action的時候,系統會調用activity的

onOptionsItemSelected()

回調方法,并且通過

MeunItem

對象來表明哪一個action被點選,在

onOptionsItemSelected()

中,調用

MenuItem.getItemId()

方法來确定被點選的action,

此方法傳回的ID就是你在

<item>

中為

android:id

定義的值。

例如,下面的代碼檢查了哪一個action被點選,用過沒有辨識出來使用者點選的那個action,就會調用父類中的方法:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_settings:
            // User chose the "Settings" item, show the app settings UI...
            return true;

        case R.id.action_favorite:
            // User chose the "Favorite" action, mark the current item
            // as a favorite...
            return true;

        default:
            // If we got here, the user's action was not recognized.
            // Invoke the superclass to handle it.
            return super.onOptionsItemSelected(item);

    }
}
           
該文章翻譯自android官方文檔,絕對忠于原著,無删改,如有錯誤,敬請指正!

譯–ToolBar(三)