ToolBar(5.0以後替代ActionBar)

這篇文章因爲是臺灣人寫的,語言風格很別緻。本文在原文的基礎上做了一些微調(主要是繁體字的問題)。

今年(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 嘍。

本篇所使用到的程序請到 Github 取得。

2. 基礎套用

這個階段從 toolbar_demo_checkpoint0 開始,分成下列三個部份:

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

2.1 風格(style)

風格要調整的地方有二

一在 res/values/styles.xml中

二在 /res/values-v21/styles.xml中

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

<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,代碼如下:

<resources>
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
  <!-- Base application theme. -->
  <style name="AppTheme" parent="AppTheme.Base">
  </style>
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
  <style name="AppTheme.Base" parent="Theme.AppCompat">
    <item name="windowActionBar">false</item>
    <item name="android:windowNoTitle">true</item>
  </style>
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
</resources>

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

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

2.2  界面(Layout)

在 activity_main.xml 裏面添加 Toolbar 控件:

<android.support.v7.widget.Toolbar
  android:id="@+id/toolbar"
  android:layout_height="wrap_content"
  android:layout_width="match_parent"
  android:minHeight="?attr/actionBarSize">
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
</android.support.v7.widget.Toolbar>

請記得用 support v7 裏的 toolbar,不然然只有 API Level 21 也就是 Android 5.0 以上的版本才能使用。

這裏需注意,要將 RelatvieLayout 裏的四個方向的padding 屬性去掉,並記得將原本的 Hello World 設爲 layout_below="@+id/toolbar" ,否則會看到像下面這樣的錯誤畫面。

2.3 程序 (Java)

在 MainActivity.java 中加入 Toolbar 的聲明:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

聲明後,再將之用 setSupportActionBar 設定,Toolbar即能取代原本的 actionbar 了,此階段完成畫面如下:

完整代碼見:toolbar_demo_checkpoint1


3. 自定義顏色(Customization color)

這個階段將從 toolbar_demo_checkpoint1 接着往下進行:


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

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

  2. App bar 底色

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

  3. navigationBarColor(導航欄底色):

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

  1. 主視窗底色:windowBackground

也因此在這個階段,我們需要設定的地方有三,一是 style中(res/values/styles.xml)

<style name="AppTheme.Base" parent="Theme.AppCompat">
  <item name="windowActionBar">false</item>
  <item name="android:windowNoTitle">true</item>
  <!-- Actionbar color -->
  <item name="colorPrimary">@color/accent_material_dark</item>
  <!--Status bar color-->
  <item name="colorPrimaryDark">@color/accent_material_light</item>
  <!--Window color-->
  <item name="android:windowBackground">@color/dim_foreground_material_dark</item>
</style>

再來是 v21 的style中 (res/values-v21/styles.xml)

<style name="AppTheme" parent="AppTheme.Base">
  <!--Navigation bar color-->
  <item name="android:navigationBarColor">@color/accent_material_light</item>
</style>

最後,就是爲了本篇的主角 – Toolbar 的 background 進行設定。

<android.support.v7.widget.Toolbar
  android:id="@+id/toolbar"
  android:layout_height="wrap_content"
  android:layout_width="match_parent"
  android:background="?attr/colorPrimary"
  android:minHeight="?attr/actionBarSize">
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
</android.support.v7.widget.Toolbar>


在本範例中,toolbar 是設定來在 activity_main.xml,對其設定 background 屬性: android:background="?attr/colorPrimary" ,這樣就可以使之延用 Actionbar 的顏色設定嘍。

最後,再來看一下結果畫面。

完整代碼見: toolbar_demo_checkpoint2

4. 控件 (component)

本階段將從 toolbar_demo_checkpoint2 接續,在還未於 <android.support.v7.widget.Toolbar/>  標籤中,自行添加元件的 toolbar 有幾個大家常用的元素可以使用,請先見下圖:


大抵來說,預設常用的幾個元素就如圖中所示,接着就依序來說明之:

  1. setNavigationIcon
    即設定 up button 的圖標,因爲 Material 的介面,在 Toolbar這裏的 up button樣式也就有別於過去的 ActionBar 哦。

  2. setLogo
    APP 的圖標。

  3. setTitle
    主標題。

  4. setSubtitle
    副標題。

  5. setOnMenuItemClickListener
    設定菜單各按鈕的動作。

先來看到菜單外的代碼,在 MainActivity.java 中:

先來看到

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                
// App Logo
toolbar.setLogo(R.drawable.ic_launcher);
// Title
toolbar.setTitle("My Title");
// Sub Title
toolbar.setSubtitle("Sub title");
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                
setSupportActionBar(toolbar);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                
// Navigation Icon 要設定在 setSupoortActionBar 纔有作用
// 否則會出現 back button
toolbar.setNavigationIcon(R.drawable.ab_android);

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

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

<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">
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
  <item android:id="@+id/action_edit"
        android:title="@string/action_edit"
        android:orderInCategory="80"
        android:icon="@drawable/ab_edit"
        app:showAsAction="ifRoom" />
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
  <item android:id="@+id/action_share"
        android:title="@string/action_edit"
        android:orderInCategory="90"
        android:icon="@drawable/ab_share"
        app:showAsAction="ifRoom" />
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
  <item android:id="@+id/action_settings"
        android:title="@string/action_settings"
        android:orderInCategory="100"
        app:showAsAction="never"/>
</menu>

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

private Toolbar.OnMenuItemClickListener onMenuItemClick = new Toolbar.OnMenuItemClickListener() {
  @Override
  public boolean onMenuItemClick(MenuItem menuItem) {
    String msg = "";
    switch (menuItem.getItemId()) {
      case R.id.action_edit:
        msg += "Click edit";
        break;
      case R.id.action_share:
        msg += "Click share";
        break;
      case R.id.action_settings:
        msg += "Click setting";
        break;
    }
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                
    if(!msg.equals("")) {
      Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
    }
    return true;
  }
};

將onMenuItemClick監聽者設置給toolbar

setSupportActionBar(toolbar);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
...
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
// Menu item click 的監聽事件一樣要設定在 setSupportActionBar 纔有作用
toolbar.setOnMenuItemClickListener(onMenuItemClick);

和 setNavigationIcon 一樣,需要將之設定在 setSupportActionBar 之後纔有作用。執行上面的代碼便會得到下面的界面。

完完整程序見:toolbar_demo_checkpoint3

5. 總結

在這樣的架構設計下,ToolBar直接成了Layout中可以控制的東西,相對於過去的actionbar來說,設計與可操控性大幅提升。

本文上面的解釋中用到的完成代碼:toolbar demo check point 0 ~ 4,請到Github 取得。

最後再附上一個界面上常用的屬性說明圖:

這裏按照圖中從上到下的順序做個簡單的說明:

  • colorPrimaryDark


    • 狀態欄背景色。

    • 在 style 的屬性中設置。

  • textColorPrimary


    • App bar 上的標題與更多菜單中的文字顏色。

    • 在 style 的屬性中設置。

  • App bar 的背景色


    • Actionbar 的背景色設定在 style 中的 colorPrimary。

    • Toolbar 的背景色在layout文件中設置background屬性。

  • colorAccent


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

    • 在 style 的屬性中設置。

  • colorControlNormal


    • 各控制元件的預設顏色。

    • 在 style 的屬性中設置

  • windowBackground


    • App 的背景色。

    • 在 style 的屬性中設置

  • navigationBarColor


    • 導航欄的背景色,但只能用在 API Level 21 (Android 5) 以上的版本

    • 在 style 的屬性中設置


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




Android之官方導航欄之Toolbar(Toolbar+DrawerLayout+ViewPager+PagerSlidingTabStrip)



通過前幾篇文章,我們對Android的導航欄有了一定的瞭解認識,本次文章將對Toolbar進行綜合應用,主要結合DrawerLayout、ViewPager、PagerSlidingTabStrip一起使用。

PagerSlidingTabStrip是github上一個開源庫,地址爲: https://github.com/astuetz/PagerSlidingTabStrip

DrawerLayout之前有過介紹,在此不在過多介紹。

先看佈局文件:

<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context="com.jredu.MainActivity"><android.support.v7.widget.Toolbar
android:id="@+id/toolbar"android:layout_width="match_parent"android:layout_height="wrap_content"android:background="?attr/colorPrimary"android:minHeight="?attr/actionBarSize"/><android.support.v4.widget.DrawerLayout
android:id="@+id/drawerLayout"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_below="@id/toolbar"><LinearLayout
android:id="@+id/main"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><com.jredu.PagerSlidingTabStrip
android:id="@+id/tabs"style="@style/pagerTabStype"android:layout_width="match_parent"android:layout_height="48dip"android:background="@drawable/background_tabs"/><android.support.v4.view.ViewPager
android:id="@+id/pager"android:layout_width="match_parent"android:layout_height="wrap_content"tools:context=".MainActivity"/></LinearLayout><LinearLayout
android:id="@+id/left"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_gravity="start"android:background="#fff"android:orientation="vertical"><LinearLayout
android:layout_width="match_parent"android:layout_height="wrap_content"android:gravity="center_vertical"android:orientation="horizontal"android:paddingTop="30dp"><ImageView
android:layout_width="80dp"android:layout_height="80dp"android:src="@drawable/ic_launcher"/><LinearLayout
android:layout_width="wrap_content"android:layout_height="wrap_content"android:orientation="vertical"android:paddingLeft="20dp"><TextView
android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="用戶名"android:textSize="18sp"/><TextView
android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="身份"android:textSize="18sp"/></LinearLayout></LinearLayout></LinearLayout></android.support.v4.widget.DrawerLayout></RelativeLayout>

佈局文件很簡單,首先將整個佈局劃分爲兩個部分,上面是Toolbar,下面是DrawerLayout,在DrawerLayout裏面有分爲兩個部分,分別是主佈局和側邊佈局。側邊佈局沒啥好說的,主要是主佈局,在主佈局裏面,上面部分是PagerSlidingTabStrip,下面部分是ViewPager。

佈局文件完成之後,我們來看java文件,首先將Toolbar和DrawerLayout使用ActionBarDrawerToggle關聯起來,代碼如下:

Toolbar boolBar = (Toolbar)findViewById(R.id.toolbar);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawerLayout);
boolBar.setTitle("傑瑞教育");
setSupportActionBar(boolBar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, boolBar,R.string.drawer_open, R.string.drawer_close);
mDrawerToggle.syncState();
mDrawerLayout.setDrawerListener(mDrawerToggle);

然後看看如何結合PagerSlidingTabStrip和ViewPager,PagerSlidingTabStrip很簡單,我們只需要將庫裏的java文件和所需要的attr文件拷到我們的項目裏面即可。

tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
        pager = (ViewPager) findViewById(R.id.pager);
        MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager());
        pager.setAdapter(adapter);
    tabs.setViewPager(pager);

通過PagerSlidingTabStrip的setViewPager方法即可將兩個組件關聯起來。不過要想實現如上效果,還必須編寫樣式,具體如下:

<style name="AppTheme" parent="AppBaseTheme">
    <itemname="colorPrimary">#1570A6</item>
    <itemname="actionBarSize">50dp</item>
    <itemname="windowActionBar">false</item>
    <itemname="titleTextAppearance">@style/CustomTitleTextAppearance</item>
  </style>
  <stylename="CustomTitleTextAppearance">
<item name="android:textColor">#fff</item>
<item name="android:textSize">20sp</item>
</style>
  <!-- PagerSlidingTabStrip的自定義樣式 -->
  <stylename="pagerTabStype">
<item name="pstsShouldExpand">true</item>
<item name="pstsDividerColor">#00000000</item>
<item name="pstsUnderlineHeight">1dp</item>
<item name="pstsIndicatorHeight">3dp</item>
<item name="pstsIndicatorColor">#1570A6</item>
</style>

需要說明的的PagerSlidingTabStrip沒有提供選中tab字體顏色的方法,在這裏可自行修改源碼實現。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章