Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Demo3 懸浮按鈕:FloatActionButton(Design Support Library)

編輯:關於 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

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved