編輯:關於 Android 程式設計
從 Demo3 開始,接下來會介紹 Design Support 組件庫中幾個常用組件,首先就從 Design Support Library 說起。Android Design Support Library 是 Google I/O 2015 大會上官方釋出的開源組件庫,收錄了各種符合 Material Design 風格的組件,今天要講的 FloatActionButton 就是其中之一。
要使用 Design Support Library,首先得在專案中引入這個庫。由於是官方提供的庫,用最傳統的 compile 語句引用即可。操作如下:在專案資源管理器中打開 Gradle Scripts → build.gradle(Module: app),你會看到各種應用程式的設定:

留意方塊中的語句,那是建立工程時 Android Studio 自動幫我們導入的 V7 支持包。接下來只要在其下方加上一條引用 Design Support Library 的語句:
compile 'com.android.support:design:23.3.0'
加入引用後,按下 Sync Now,Android Studio 就會把 Design Support Library 導入專案:

之後就能在專案資源管理器的 External Libraries 資料夾中看到 design-23.3.0 庫(版本依實際情況而定)。順帶一提,日後要使用 design support library 的組件,也都要先引用這個庫。
進入主題。FloatActionButton 是 ImageButton 的繼承類,用法與普通 Button 類似,但由於具備更多表現屬性,使用重點其實落在佈局上。
main_layout.xml:
<relativelayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<include layout="@layout/toolbar">
<android.support.design.widget.floatingactionbutton
android:id="@+id/bMain_Float" app:fabSize="normal"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:src="@android:drawable/ic_dialog_email">
</android.support.design.widget.floatingactionbutton>
</include>
</relativelayout>
上面我們像 ImageButton 一樣定義即可。另外,FloatActionButton 可以透過 fabSize 屬性指定大小,正常是 normal,還有一個更小的 mini 模式,你也可以試著改成 mini 運行看看效果。
運行後的佈局效果如下:

關於填充色,有兩個重要屬性:backgroundTint 與 rippleColor,分別代表普通狀態與點擊狀態下的填充色(普通狀態下浮起會有陰影,點擊後陰影範圍會變大)。其中 backgroundTint 預設值是主題中的 colorAccent,rippleColor 預設值是 colorControlHighlight。一般做法是直接在佈局中指定這兩個顏色。
FloatActionButton 最大的特色是懸浮效果,因此與立體感相關的屬性也很重要,這裡同樣涉及兩個屬性:elevation 與 pressedTranslationZ,分別代表普通狀態與點擊時的陰影大小。設定好之後,最終佈局如下:
<relativelayout android:layout_height="match_parent"
android:layout_width="match_parent" android:orientation="vertical"
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto">
</relativelayout>
至於點擊事件,跟 Button 一樣,這裡就不再贅述。最終效果:

有趣的一點是,FloatActionButton 常見的用法之一是點擊後讓它動起來,這就涉及 Android 的動畫效果。有興趣的讀者可以參考郭霖大神關於屬性動畫的專文《Android 屬性動畫完全解析(上)》,裡面對原理講得非常細緻,值得細讀。
Demo 源碼下載:Demo3:FloatActionButton
Android 5.0 Settings 原始碼簡要分析
概述 近來有機會接觸 Android 原始碼,趁此機會記錄一些收穫。本文針對 L(5.0)平台上 Settings 模組的正常啟動流程做一個簡要分析,並嘗試解析 Sett
Android 全域未捕捉異常與崩潰處理實戰
本文示範如何為 App 建立一道「安全網」:當程式爆發未捕捉異常時,不再直接閃退,而是彈出一個友善的提示對話框,同時把完整的錯誤堆疊自動寫入 SD 卡的 crash 目錄
Android Handler 基本用法:子線程更新 UI 的標準解法
Android 有個硬性規則:UI 只能在主線程(UI 線程)操作。但耗時任務又必須放在子線程執行,兩者之間的橋樑就是 Handler。本文整理 Handler 的核心概
Android 傳感器實戰:用加速度計做一個「搖一搖聽音樂」
上一篇我們認識了 Android 的傳感器體系,這次直接動手做個小玩具——搖一搖播放音樂。原理很簡單:讀取加速度傳感器的三軸數值,當搖晃劇烈到一定程度時觸發播放。 先看