FloatingActionButton是Support Design Library庫中引入的一個新的控件,外觀時尚新穎,受到很多開發者的好評。
如何使用FloatingActionButton
使用FloatingActionButton其實非常簡單隻需要在布局檔案中引入控件即可,不過它的屬性有點多,我們先來介紹一下它的屬性。
- android:src:FAB中顯示的圖示.
- app:backgroundTint:正常的背景顔色 ,這裡是ColorStateList類型
- app:rippleColor:按下時的背景顔色
- app:elevation:正常的陰影大小
- app:pressedTranslationZ:按下時的陰影大小
- app:layout_anchor:設定FAB的錨點,即以哪個控件為參照設定位置
- app:layout_anchorGravity:FAB相對于錨點的位置
- app:fabSize:FAB的大小,normal或mini(分别對應56dp和40dp)
- app:borderWidth:邊框大小,最好設定成0dp否則會有邊框
- android:clickable:一定要設定成true否則沒有點選效果
講完屬性接下來實作一下效果
xml布局檔案
<FrameLayout
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"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_gravity="end|bottom"
android:id="@+id/floatbutton"
app:elevation="6dp"
android:clickable="true"
app:borderWidth="0dp"
android:backgroundTint="@color/fabbg"
app:rippleColor="#0097a7"
android:layout_marginBottom="20dp"
android:layout_marginRight="20dp"
android:src="@drawable/ic_logo"
app:pressedTranslationZ="12dp"
android:layout_height="wrap_content" />
</FrameLayout>
color/fabbg.xml檔案,這個需要在res目錄下建立color檔案夾
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIn5GcuYmYyYWM3MWZ1gjYjNDNzEmY5UGZjJzMyATMxI2MlNmYfdWbp9CXt92Yu4GZjlGbh5SZslmZxl3Lc9CX6MHc0RHaiojIsJye.png)
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="false" android:color="#00b8d4"/>
<item android:state_focused="true" android:color="#00e5ff"/>
</selector>
FloatingActionButton的點選事件與Button的實作方式一樣,這裡不予示範
運作效果
GIF.gif