編輯:Android 資訊
年前我發過一篇介紹 Translucent System Bar 特性的文章《Translucent System Bar 的最佳實踐》,收到不少開發者的關注和反饋。今天來寫第二篇,全面聊聊 Toolbar 的用法。說到 Toolbar,可能還有不少同學比較陌生,沒關係,接著往下看。
Toolbar 是 Android 5.0 開始推出的一個 Material Design 風格導航控件,Google 非常推薦用它取代過去的 Actionbar。相比 Actionbar,Toolbar 明顯靈活得多:它不必像 Actionbar 那樣固定在 Activity 頂部,而是可以擺到界面的任意位置。此外,Google 也給開發者留了很多可定製的余地,這些屬性在 API 文檔裡都有詳細介紹,例如:

Toolbar 支持的特性
總之,相比 Actionbar,Toolbar 讓我感受到 Google 滿滿的誠意。是否已經躍躍欲試了?接下來,我們一步步看怎麼用它(其實這是我使用 Toolbar 踩坑填坑的血淚史,你們接著看,我先擦擦眼淚……)。
前面提到 Toolbar 從 Android 5.0 才有,為了向下兼容,Google 自然也推出了兼容版。我們需要在工程中引入 appcompat-v7 兼容包,使用 android.support.v7.widget.Toolbar 進行開發。先看代碼結構,重點部分已用紅圈圈出:

關鍵部分代碼
先看 ToolbarActivity 的運行效果。

ToolbarActivity 效果圖
按效果圖,從左到右依次是我們前面提到的導航欄圖標、App 的 logo、標題和子標題、自定義控件,以及 ActionMenu。接著看佈局和代碼。
首先在佈局文件 activity_tool_bar.xml 中加入 Toolbar 控件。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/color_0176da"> <!--自定義控件--> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Clock" /> </android.support.v7.widget.Toolbar> </LinearLayout>
接著在 base_toolbar_menu.xml 中加入 action menu 菜單項。
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="https://schemas.android.com/apk/res/android" xmlns:app="https://schemas.android.com/apk/res-auto"> <item android:id="@id/action_search" android:icon="@mipmap/ic_search" android:title="@string/menu_search" app:showAsAction="ifRoom" /> <item android:id="@id/action_notification" android:icon="@mipmap/ic_notifications" android:title="@string/menu_notifications" app:showAsAction="ifRoom" /> <item android:id="@+id/action_item1" android:title="@string/item_01" app:showAsAction="never" /> <item android:id="@+id/action_item2" android:title="@string/item_02" app:showAsAction="never" /> </menu>
最後到 ToolbarActivity 裡拿到 Toolbar 控件,並在代碼中做各種 setXXX 操作。
/** * Toolbar的基本使用 */ public class ToolBarActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tool_bar); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setNavigationIcon(R.mipmap.ic_drawer_home);//設置導航欄圖標 toolbar.setLogo(R.mipmap.ic_launcher);//設置app logo toolbar.setTitle("Title");//設置主標題 toolbar.setSubtitle("Subtitle");//設置子標題 toolbar.inflateMenu(R.menu.base_toolbar_menu);//設置右上角的填充菜單 toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { int menuItemId = item.getItemId(); if (menuItemId == R.id.action_search) { Toast.makeText(ToolBarActivity.this , R.string.menu_search , Toast.LENGTH_SHORT).show(); } else if (menuItemId == R.id.action_notification) { Toast.makeText(ToolBarActivity.this , R.string.menu_notifications , Toast.LENGTH_SHORT).show(); } else if (menuItemId == R.id.action_item1) { Toast.makeText(ToolBarActivity.this , R.string.item_01 , Toast.LENGTH_SHORT).show(); } else if (menuItemId == R.id.action_item2) { Toast.makeText(ToolBarActivity.this , R.string.item_02 , Toast.LENGTH_SHORT).show(); } return true; } }); } }至此 Toolbar 的基本用法就完成了——注意,只是基本用法而已!下面幾點需要特別留意:
坑一:xml 佈局文件中 Toolbar 屬性設置無效
剛開始用 Toolbar 時,我的佈局是這樣寫的:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/color_0176da" android:logo="@mipmap/ic_launcher" android:navigationIcon="@mipmap/ic_drawer_home" android:subtitle="456" android:title="123"> <!--自定義控件--> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Clock" /> </android.support.v7.widget.Toolbar> </LinearLayout>
真機跑起來後,看到的是這樣:

Toolbar 屬性設置無效
此時心中真是萬馬奔騰:除了背景色和 TextView 生效,說好的 logo、navigationIcon、subtitle、title 都跑哪去了?編譯器不報錯又沒效果,參考其他開發者的用法後,我找到了解法——在根佈局加入自定義屬性的命名空間:
xmlns:toolbar="https://schemas.android.com/apk/res-auto"(這裡的 toolbar 可以換成你喜歡的名字,做過自定義控件的同學應該很熟悉)
然後把所有用 android:xxx 設置無效的,改用 toolbar:xxx 即可生效。最終佈局代碼如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:toolbar="https://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/color_0176da" toolbar:navigationIcon="@mipmap/ic_drawer_home" toolbar:logo="@mipmap/ic_launcher" toolbar:subtitle="456" toolbar:title="123"> <!--自定義控件--> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Clock" /> </android.support.v7.widget.Toolbar> </LinearLayout>
這樣就解決了 xml 屬性失效的問題。為什麼會這樣?我猜是因為這是兼容版控件,那些屬性定義在兼容包而非默認的 Android SDK 裡,所以要額外引入命名空間。至於 IDE 為何也不報錯,大概只能算 bug 了。
坑二:Action Menu Item 的文字顏色設置無效
系統默認設定了 ActionMenu 每個 Item 的文字顏色和大小,像 ToolbarActivity 在原生 5.1 系統下的默認效果就是這樣:

Android 5.1 默認的 ActionMenu Item 風格
若想改動 item 文字顏色,我按網上普遍的方案做了兩步:
在 styles.xml 自定義一個 Theme,並設置 actionMenuTextColor(注意:不是 android:actionMenuTextColor)。
<style name="Theme.ToolBar.Base" parent="Theme.AppCompat.Light.NoActionBar"> <item name="actionMenuTextColor">@color/color_red</item> </style>
在佈局的 Toolbar 中設置 popupTheme(注意:是 toolbar:xxx,不是 android:xxx)。
<android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/color_0176da" toolbar:popupTheme="@style/Theme.ToolBar.Base"> <!--自定義控件--> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Clock" /> </android.support.v7.widget.Toolbar>
結果文字顏色紋絲不動。說好的變色呢……最後在 StackOverflow 找到一個還不錯的方案:把 actionMenuTextColor 換成 android:textColorPrimary 即可,最終效果如下。

成功修改 actionmenu item 文字的顏色
這方法有個小缺點:如果把自定義控件換成 Button,你會發現 Button 默認文字顏色也跟著變紅了。若有更好的方案,歡迎留言賜教。想改 ActionMenu Item 文字大小,也可以在 theme 裡加上:
<item name="android:textSize">20sp</item>
以上就是目前使用 Toolbar 比較折騰的幾個坑,真心希望 Google 能再優化優化,別讓開發者繼續踩雷。
為了加深對 Toolbar 的開發體驗,我們用它來實現知乎主頁的效果。先看知乎主頁長啥樣。

Android 5.1 上知乎主頁效果圖
前面內容若看明白了,想撸出這個界面無非幾分鐘的事,直接上代碼。
ZhiHuActivity 界面代碼:
public class ZhiHuActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_zhi_hu); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.inflateMenu(R.menu.zhihu_toolbar_menu); toolbar.setNavigationIcon(R.mipmap.ic_drawer_home); toolbar.setTitle(R.string.home_page); toolbar.setTitleTextColor(getResources().getColor(android.R.color.white)); } }zhihu_toolbar_menu.xml 菜單:
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="https://schemas.android.com/apk/res/android" xmlns:app="https://schemas.android.com/apk/res-auto"> <item android:id="@id/action_search" android:icon="@mipmap/ic_search" android:title="@string/menu_search" app:showAsAction="ifRoom" /> <item android:id="@id/action_notification" android:icon="@mipmap/ic_notifications" android:title="@string/menu_notifications" app:showAsAction="ifRoom" /> <item android:id="@id/action_settings" android:orderInCategory="100" android:title="@string/menu_settings" app:showAsAction="never" /> <item android:id="@id/action_about" android:orderInCategory="101" android:title="@string/menu_about_us" app:showAsAction="never" /> </menu>
activity_zhi_hu.xml 佈局:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/color_0176da" android:theme="@style/Theme.ToolBar.ZhiHu"> </android.support.v7.widget.Toolbar> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/white"> <ImageView android:layout_width="60dp" android:layout_height="60dp" android:layout_centerInParent="true" android:background="@mipmap/ic_zhihu_logo" /> </RelativeLayout> </LinearLayout>
styles.xml 中的 Theme.ToolBar.ZhiHu,用來給 Toolbar 設 android:theme:
<resources> ... ... <style name="Theme.ToolBar.ZhiHu" parent="Theme.AppCompat.Light.NoActionBar"> <item name="actionOverflowButtonStyle">@style/ActionButton.Overflow.ZhiHu</item> </style> <style name="ActionButton.Overflow.ZhiHu" parent="android:style/Widget.Holo.Light.ActionButton.Overflow"> <item name="android:src">@mipmap/ic_menu_more_overflow</item> </style> </resources>
最終得到這樣的效果。

Android 5.1 上仿知乎主頁面效果
這裡給 Toolbar 設 android:theme 主要是為了替換右上角那三個點的溢出圖標,不設的話就會是系統默認樣子。

不設置 Theme 的效果
最後再給知乎主頁做個小優化:它在 Android 4.4 上還能看到一條黑乎乎的通知欄,於是我把 Toolbar 和 Translucent System Bar 結合起來,改進成下面的樣子(附上 4.4 和 5.1 的效果)。

Android 4.4 上改進版的知乎主頁

Android 5.1 上改進版的知乎主頁
如果還不會用 Translucent System Bar,可以看我上一篇《Translucent System Bar 的最佳實踐》。
關於 Toolbar 的用法就介紹到這。本來以為很簡單就能上手,結果還是有不少坑要填,果然應了那句老話:
紙上得來終覺淺,絕知此事要躬行
想更深入了 Toolbar 設計的同學,也可以看看官方文檔(自備梯子)。需要源碼的朋友,請戳:https://github.com/D-clock/AndroidSystemUiTraining
Android 為何比 iOS 卡?從 1G 記憶體說起
日前一位認證為小米員工的人在微博上說:「iPhone 6 使用者都不在意 1G 記憶體不夠,紅米 2 的 1G 夠用了,保持流暢的秘訣就是少裝 App。」後續發展大家都知
Android 左右滑動效果的程式碼實作
左右滑動切換的互動在 Android 應用裡隨處可見,那它究竟是如何做到的呢?本文以一個圖片滑動的範例為切入點,逐段拆解實作細節。 本範例要達成的效果是:以手指左右滑動來
Android ActionBar 導航欄完整用法解析
一、ActionBar 概覽 ActionBar 是 Android 3.0 之後新增的元件,主要用來標示應用所在位置、提供相關操作入口,並承擔全域導航職責。真正開始使用
Android UI 元件系列:LinearLayout 線性版面配置
LinearLayout 是一個以線性方向排列子 View 的 ViewGroup,方向可以是水平,也可以是垂直。 你可以重複巢狀使用多層 LinearLayout;不過