Android - ToolBar詳解

原碼下載地址:

2014 的 google i/o 發表令多數人爲之一亮的 material design,而 google 也從「google i/o 2014」 開始,
大家也陸陸續續地看到其更新的 android app 皆套用了這個設計介面。
當然,這個設計介面著實讓大家感到驚豔外,更讓 android 開發者開始擔心未來 app 的界面處理了。

不過,所幸有着之前 actionbar 的經驗後,android 也很快地在 support library 裏面提供了相對應的 api 給開發者使用,
本篇就爲各位介紹 – toolbar,這是用來取代過去 actionbar 的控件,而現在於 material design 中也對之有一個統一名稱:app bar,
在未來的 android app 中,就以 toolbar 這個元件來實作之。

  1. 概述
    Android 3.0 Android 推了 ActionBar 這個控件,而到了2013 年 Google 開始大力地推動所謂的 android style,
    想要逐漸改善過去 android 紛亂的界面設計,希望讓終端使用者儘可能在 android 手機有個一致的操作體驗。
    ActionBar 過去最多人使用的兩大套件就是 ActionBarSherlock 以及官方提供在 support library v 7 裏的 AppCompat。

    既然會有本篇跟各位介紹的 Toolbar,也意味着官方在某些程度上認爲 ActionBar 限制了 android app 的開發與設計的彈性,
    而在 material design 也對之做了名稱的定義:App bar。
    接下來將爲各位分成幾個階段進行說明,如何在 android app 中用 toolbar 這個控件來做出一個基本的 app bar 嘍。
    總攬:
    這裏寫圖片描述

2.基礎套用
這個階段分爲3個部分:

風格 (style)
界面 (layout)
程序 (java)

2.1 風格(style)

風格要調整的地方有二

一在 res/values/styles.xml中

二在 /res/values-v21/styles.xml中 (API >=21 也就是5.0及以上)

爲了之後設定方便,我們先在 res/values/styles.xml 裏增加一個名爲 AppTheme.Base的風格

res/values/styles.xml
<style name="AppTheme.Base" parent="Theme.AppCompat">
    <item name="windowActionBar">false</item>
    <item name="android:windowNoTitle">true</item>
</style>

因爲此範例只使用 Toolbar,所以我們要將讓原本的 ActionBar 隱藏起來,
然後將原本 AppTheme 的 parent 屬性 改爲上面的AppTheme.Base,代碼如下:

res/values/styles.xml
<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="AppTheme.Base">
    </style>

    <style name="AppTheme.Base" parent="Theme.AppCompat">
        <!--ActionBar隱藏,這裏使用ToolBar-->
        <item name="windowActionBar">false</item>

        <del><item name="android:windowNoTitle">true</item></del>
        <!-- 使用 API Level 22 編譯的話,要拿掉前綴字 -->
        <item name="windowNoTitle">true</item>
    </style>
</resources>

再來調整Android 5.0的style: /res/values-v21/styles.xml,也將其 parent 屬性改爲 AppTheme.Base:

res/values-v21/styles.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="AppTheme" parent="AppTheme.Base">
    </style>
</resources>

2.2界面(Layout)
在 activity_main.xml 裏面添加 Toolbar 控件:

activity_main.xml
<!-- ?attr/actionBarSize -> toolbar的高度是原先的actionbar的高度 -->
<android.support.v7.widget.Toolbar
     android:id="@+id/toolbar"
     android:layout_height="?attr/actionBarSize"
     android:layout_width="match_parent" >  
</android.support.v7.widget.Toolbar>

(1)android.support.v7依賴 moduled右擊/open module setting/Dependencies/右邊+號/library dependencies/選擇v7
(2)請記得用 support v7 裏的 toolbar,不然然只有 API Level 21 也就是 Android 5.0 以上的版本才能使用。
(3)這裏需注意,要將 RelatvieLayout 裏的四個方向的padding 屬性去掉,並記得將原本的 Hello World 設爲 layout_below=”@+id/toolbar” ,
否則會看到像下面這樣的錯誤畫面:
toobar.blog2 (後續貼上)

2.3 程序 (Java)
在 MainActivity.java 中加入 Toolbar 的聲明:

MainActivity.java/onCreate()

mToolbar = (Toolbar) findViewById(R.id.toolbar);
// 取代原本的actionbar
// 使用該方法的時候MainActivity需要繼承於AppCompatActivity
setSupportActionBar(toolbar);

聲明後,再將之用 setSupportActionBar 設定,Toolbar即能取代原本的 actionbar 了,此階段完成畫面如下:
toolbar.blog3(後續補上)

  1. 自定義顏色(Customization color)

toolbar.blog4
上圖是將本階段要完成的結果畫面做了標示,結合下面的描述希望大家能明白。

屬性介紹:
(1)colorPrimaryDark(狀態欄底色):在風格 (styles) 或是主題 (themes) 裏進行設定。

(2)App bar底色 這個設定分爲二,
1’若你的 android app 仍是使用 actionbar ,則直接在風格 (styles) 或是主題 (themes) 裏進行設定 colorPrimary 參數即可;
2’若是採用 toolbar 的話,則要在界面 (layout) 裏面設定 toolbar 控件的 background 屬性。

(3)navigationBarColor(導航欄底色)
僅能在 API v21 也就是 Android 5 以後的版本中使用, 因此要將之設定在 res/values-v21/styles.xml 裏面。

(4)windowBackground - 主視窗底色

因此這個階段,我們需要做的設定有三個地方

res/values/styles.xml  (追加狀態欄以及Window的底色)

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="AppTheme.Base">
    </style>

    <style name="AppTheme.Base" parent="Theme.AppCompat">
        <!-- 將ActionBar隱藏,這裏使用ToolBar-->
        <item name="windowActionBar">false</item>

        <del><item name="android:windowNoTitle">true</item></del>
        <!-- 使用 API Level 22 編譯的話,要拿掉前綴字 -->
        <item name="windowNoTitle">true</item>

+       <!--Status bar color-->
+       <item name="colorPrimaryDark">@color/accent_material_light</item>

+       <!-- Actionbar color -->
+       <!-- 若是使用的是ActionBar,colorPrimary屬性就夠了;  但是若是ToolBar 還需要在toolbar 控件中設置background 屬性 -->
+       <item name="colorPrimary">@color/accent_material_dark</item>

+       <!-- Window color-->
+       <item name="android:windowBackground">@color/dim_foreground_material_dark</item>
    </style>
</resources>
res/values-v21/styles.xml (追加底部導航欄底色)
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="AppTheme" parent="AppTheme.Base">
+       <!-- Navigation bar color -->
+       <item name="android:navigationBarColor">@color/accent_material_light</item>
    </style>
</resources>
activity_main.xml (追加Toolbar底色)

<!-- ?attr/actionBarSize -> toolbar的高度是原先的actionbar的高度 -->
<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_height="?attr/actionBarSize"
    android:layout_width="match_parent" 
+   android:background="?attr/colorPrimary" >
</android.support.v7.widget.Toolbar>

最後,再來看一下結果畫面(只看顏色)

Toolbar.blog1

4.控件(component)

MainActivity.java/onCreat()

mToolbar = (Toolbar) findViewById(R.id.toolbar);
// App Logo
mToolbar.setLogo(R.drawable.ic_launcher);
// Title
mToolbar.setTitle("My Title");
// Sub Title
mToolbar.setSubtitle("Sub title");

// 取代原本的actionbar
// 使用該方法的時候MainActivity需要繼承於AppCompatActivity
setSupportActionBar(mToolbar);

// Navigation Icon 要設定在 setSupoortActionBar(...) 後纔有作用
// 否則會出現 back button,而不是預想設定的Icon
mToolbar.setNavigationIcon(R.drawable.ab_android);

這邊要留意的是setNavigationIcon需要放在 setSupportActionBar之後纔會生效

再來看菜單部分,需要先在res/menu/menu_main.xml左定義:

res/menu/menu_main.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">

    <!--
        1.alaways:這個值會使菜單項一直顯示在ActionBar上。
        2.ifRoom:如果有足夠的空間,這個值會使菜單顯示在ActionBar上。
        3.never:這個值菜單永遠不會出現在ActionBar是。
        4.withText:這個值使菜單和它的圖標,菜單文本一起顯示。
     -->

    <!-- orderInCategory 決定item的順序, 值越大,優先級越低-->

    <item android:id="@+id/action_edit"
        android:title="edit"
        android:orderInCategory="80"
        android:icon="@drawable/abc_ic_ab_back_mtrl_am_alpha"
        app:showAsAction="ifRoom" />

    <item android:id="@+id/action_share"
        android:title="edit"
        android:orderInCategory="90"
        android:icon="@drawable/abc_ic_menu_share_mtrl_alpha"
        app:showAsAction="ifRoom" />

    <item android:id="@+id/action_settings"
        android:title="@string/action_settings"
        android:orderInCategory="100"
        app:showAsAction="never"/>
    <item android:id="@+id/action_1"
        android:title="action_1"
        android:orderInCategory="70"
        app:showAsAction="never"/>
    <item android:id="@+id/action_2"
        android:title="action_2"
        android:orderInCategory="40"
        app:showAsAction="never"/>
    <item android:id="@+id/action_overflow"
        android:title="action_overflow"
        android:orderInCategory="10"
        app:showAsAction="never"/>
</menu>

再回到MainActivity.java 中加入OnMenuItemClickListener 的監聽者:

//設置toolBar上的MenuItem點擊事件
mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
    @Override
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_edit:
                mToast.setText("click edit");
                break;
            case R.id.action_share:
            mToast.setText("click share");
                break;
            case R.id.action_settings:
            mToast.setText("seting");
                break;
            case R.id.action_1:
            mToast.setText("1");
                break;
            case R.id.action_2:
            mToast.setText("2");
                break;
            case R.id.action_overflow:
            //彈出自定義overflow
            popUpMyOverflow();
            return true;
        }
        mToast.show();
        return true;
    }
});


注意拉:
這個時候的按鈕響應都必須在setOnMenuItemClickListener寫,不可以在重載的onOptionsItemSelected中進行相應了

此外增加了點擊action_overflow,彈出自定義的popWindow
/**
* 彈出自定義的popWindow
* 並且popwindow是貼着狀態欄的底部的
*/

public void popUpMyOverflow() {
    //獲取狀態欄高度
    Rect frame = new Rect();
    getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
    //狀態欄高度+toolbar的高度
    int yOffset = frame.top + mToolbar.getHeight();
    if (null == mPopupWindow) {
        //初始化PopupWindow的佈局
        View popView = getLayoutInflater().inflate(R.layout.action_overflow_popwindow, null);
        //popView即popupWindow的佈局,ture設置focusAble.
        mPopupWindow = new PopupWindow(popView,
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT, true);
        //必須設置BackgroundDrawable後setOutsideTouchable(true)纔會有效
        mPopupWindow.setBackgroundDrawable(new ColorDrawable());
        //點擊外部關閉。
        mPopupWindow.setOutsideTouchable(true);
        //設置一個動畫。
        mPopupWindow.setAnimationStyle(android.R.style.Animation_Dialog);
        //設置Gravity,讓它顯示在右上角。
        mPopupWindow.showAtLocation(mToolbar, Gravity.RIGHT | Gravity.TOP, 0, yOffset);
        //設置item的點擊監聽
        popView.findViewById(R.id.ll_item1).setOnClickListener(this);
        popView.findViewById(R.id.ll_item2).setOnClickListener(this);
        popView.findViewById(R.id.ll_item3).setOnClickListener(this);
    } else {
        mPopupWindow.showAtLocation(mToolbar, Gravity.RIGHT | Gravity.TOP, 0, yOffset);
    }
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.ll_item1:
    mToast.setText("哈哈");
    break;
    case R.id.ll_item2:
    mToast.setText("呵呵");
    break;
    case R.id.ll_item3:
    mToast.setText("嘻嘻");
    break;
    }
    //點擊PopWindow的item後,關閉此PopWindow
    if (null != mPopupWindow && mPopupWindow.isShowing()) {
        mPopupWindow.dismiss();
    }
    mToast.show();
}

popWindow佈局如下
res/layout/action_overflow_popwindow.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#274B5E"
    android:orientation="vertical"
    android:padding="10dp">

    <LinearLayout
        android:id="@+id/ll_item1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/abc_ic_menu_share_mtrl_alpha" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:text="哈哈"
            android:textColor="#ffffff"
            android:textSize="20sp" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/ll_item2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/abc_ic_menu_share_mtrl_alpha" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:text="呵呵"
            android:textColor="#ffffff"
            android:textSize="20sp" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/ll_item3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/abc_ic_menu_share_mtrl_alpha" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:text="嘻嘻"
            android:textColor="#ffffff"
            android:textSize="20sp" />
    </LinearLayout>
</LinearLayout>

5.總結
(1)colorPrimaryDark
狀態欄背景色。
在 style 的屬性中設置。

(2)textColorPrimary
App bar 上的標題與更多菜單中的文字顏色。

(3)App bar 的背景色
Actionbar 的背景色設定在 style 中的 colorPrimary。
Toolbar 的背景色在layout文件中設置background屬性。

(4)colorAccent
各控制元件(如:check box、switch 或是 radoi) 被勾選 (checked) 或是選定 (selected) 的顏色。

(5)colorControlNormal
各控制元件的預設顏色。
在 style 的屬性中設置

(6)windowBackground
App 的背景色。

(7)navigationBarColor
導航欄的背景色,但只能用在 API Level 21 (Android 5) 以上的版本
在 style 的屬性中設置

最後需要注意的是:使用material主題的時候,必須設定targetSdkVersion = 21,否則界面看起來是模糊的

發佈了116 篇原創文章 · 獲贊 26 · 訪問量 24萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章