編輯:關於 Android 程式設計
Android 5.0 之後,Google 開始大力推行 Material Design,其中一個重要目標就是終結此前各家主題風格雜亂的局面。上一篇我們介紹了 RecyclerView、CardView 與 Palette,這次來談談 Toolbar 與 Theme。
前置條件:使用 Toolbar 與 Material Theme 需要在模塊的 build.gradle 中引入 appcompat 庫:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.2.0'
}
如果你曾被 ActionBar 這些限制困擾過——標題位置不能隨意調整、無法塞入自定義佈局、樣式改起來處處受限——Toolbar 就是為了解決這些問題而生的。它本質上是一個放在佈局文件裡的普通容器,因此完全可配置、可自定義。
本文按以下四個部分展開:基礎使用、主題配置、常用控件設置、自定義佈局。
系統默認的主題是:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
這代表使用系統內建的 ActionBar。要改用 Toolbar,必須換成 No ActionBar 主題:
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
在 activity_main.xml 中引入 v7 包提供的 Toolbar,並且一定要給它一個 id:
<RelativeLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
關鍵是 setSupportActionBar(toolbar),它把 Toolbar 提升為 Activity 的 ActionBar,之後就能沿用原有的菜單與標題 API。

此時效果確實很樸素,還看不到任何 Material Design 的氣息——因為我們還沒配置主題。
在 styles.xml 中定義配色:
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- 導航欄底色 -->
<item name="colorPrimary">@color/accent_material_dark</item>
<!-- 狀態欄底色 -->
<item name="colorPrimaryDark">@color/accent_material_light</item>
<!-- 導航欄上的標題顏色 -->
<item name="android:textColorPrimary">@android:color/black</item>
<!-- Activity 窗口的顏色 -->
<item name="android:windowBackground">@color/material_blue_grey_800</item>
<!-- 控件點擊/獲得焦點後的顏色 -->
<item name="colorAccent">#00ff00</item>
<!-- 與 colorAccent 相反,正常狀態下控件的顏色 -->
<item name="colorControlNormal">#ff0000</item>
<!-- Button 正常狀態顏色 -->
<item name="colorButtonNormal">@color/accent_material_light</item>
<!-- EditText 輸入框中字體的顏色 -->
<item name="editTextColor">@android:color/white</item>
</style>
接著讓 Toolbar 使用主題裡的 colorPrimary 作為背景,只需在 Toolbar 標籤上加一行:
android:background="?attr/colorPrimary"

Toolbar 具備 ActionBar 的全部能力,同時暴露了更直接的 API:
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar.setTitle("主標題");
toolbar.setSubtitle("副標題");
toolbar.setLogo(R.drawable.ic_launcher);
toolbar.setNavigationIcon(android.R.drawable.ic_input_delete);
可以設置 Title(主標題)、Subtitle(副標題)、Logo 圖標與 Navigation Icon(導航按鈕)。
注意:若想用 toolbar.setTitle() 自訂標題,必須先呼叫 getSupportActionBar().setDisplayShowTitleEnabled(false) 隱藏系統默認的 Title,否則會出現標題重疊。
菜單文件寫法和傳統 ActionBar 一致,只需注意 appcompat 要求使用 app:showAsAction 命名空間:
<menu xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
tools:context=".MainActivity">
<item
android:id="@+id/action_edit"
android:icon="@drawable/abc_ic_search_api_mtrl_alpha"
android:orderInCategory="80"
android:title="查找"
app:showAsAction="always" />
<item
android:id="@+id/action_share"
android:icon="@drawable/abc_ic_menu_share_mtrl_alpha"
android:orderInCategory="90"
android:title="分享"
app:showAsAction="always" />
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:title="@string/action_settings"
app:showAsAction="never" />
</menu>
點擊事件透過 OnMenuItemClickListener 接口處理:
public class MainActivity extends AppCompatActivity
implements Toolbar.OnMenuItemClickListener {
// 記得在 onCreate 中註冊
toolbar.setOnMenuItemClickListener(this);
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_edit:
Toast.makeText(this, "查找按鈕", Toast.LENGTH_SHORT).show();
break;
case R.id.action_share:
Toast.makeText(this, "分享按鈕", Toast.LENGTH_SHORT).show();
break;
}
return false;
}
}

Toolbar 繼承自 ViewGroup,也就是說它是個容器,可以直接塞入任意佈局。這也順勢解決了「標題無法居中」的老問題:
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="add" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_gravity="center_vertical"
android:text="標題"
android:textSize="18sp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:background="@drawable/abc_ic_menu_share_mtrl_alpha" />
</RelativeLayout>
</android.support.v7.widget.Toolbar>

從此標題居中、左側放 logo、右側放自定義按鈕這類需求都能自由實現。
只會用 Toolbar 還不夠,Theme 才是統一全局風格的槓桿。以下是一組典型的 Material 配色:

各屬性的作用:
1. colorPrimary:Toolbar 導航欄底色,也是全局的主色調。
2. colorPrimaryDark:狀態欄底色,注意這項只在 Android 5.0 以上生效。
3. android:textColorPrimary:當前 Activity 文本的默認顏色。
4. android:windowBackground:Activity 窗體的基準顏色。
5. colorAccent:CheckBox、RadioButton、SwitchCompat 等控件被選中時的高亮色。
6. colorControlNormal:上述控件在正常狀態下的顏色。
7. colorButtonNormal:Button 在正常狀態下的顏色。
8. editTextColor:EditText 輸入框內文字顏色。
把這幾個屬性調對,即使不改一行佈局代碼,整個 App 的視覺基調也會煥然一新。若想支援 Android 5.0 以下的設備,則需搭配 appcompat 的主題(Theme.AppCompat.Light.NoActionBar)並注意部分屬性需使用不带 android: 前綴的版本。
通信組件之 Intent 的基本使用大全
(一)概述 本節引言: 上一節結束後,意味著 Android 四大組件我們都學完了。而這一節要探討的,是四大組件之間的樞紐——Intent(意圖),名副其實的 Andro
Android群英傳筆記第十章:Android性能優化
一、布局優化 流暢的界面離不開合理的布局。Android 通過 VSYNC 信號驅動 UI 渲染,理想狀態下每一幀應在 16ms 內完成。若布局過於複雜或绘制邏輯過重,就
Android 退出應用程式的另一種方法:finishAffinity() 一行程式碼關閉任務
在 Android 中,退出應用程式有許多做法,例如註冊廣播、維護 Activity 列表、遍歷 finish,或使用 startActivityForResult。本文
工廠模式到底有什麼用?用麥當勞點餐與線程池一次講透
先把那個心結說開 很多人第一次接觸工廠模式時都會有同樣的疑問:既然對象的職責就是「被創建」,那直接 new 一個不就完了,為什麼還要再包一層工廠類,讓工廠去幫你 new?