Skip to content

悬浮操作按钮 (FAB)

源:Floating action buttons

悬浮操作按钮 (FAB) 代表屏幕上的主要操作。

FAB 类型

变体与尺寸

M3 提供了多种尺寸的 FAB,以适应不同的屏幕布局:

变体描述适用场景
Small FAB40dp已弃用,建议仅用于微调 UI
FAB (Regular)56dp标准尺寸,最常用
Large FAB96dp极高强调度,适用于宽屏或强调单一入口
Extended FAB自动宽度带有文字标签的 FAB

代码实现

基础用法

xml
<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="16dp"
    app:srcCompat="@drawable/ic_add"
    android:contentDescription="添加" />
kotlin
// 显示
fab.show()

// 隐藏
fab.hide()

扩展型 FAB (Extended FAB)

扩展型 FAB 允许你在图标旁边添加文字说明。

xml
<com.google.android.material.extendedfloatingactionbutton.ExtendedFloatingActionButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="撰写"
    app:icon="@drawable/ic_edit" />

核心属性

属性描述默认值
app:backgroundTint按钮背景颜色?attr/colorPrimaryContainer
app:tint图标着色?attr/colorOnPrimaryContainer
app:elevation海拔(阴影)6dp
app:shapeAppearance圆角形状默认为全圆角或特定切角

CoordinatorLayout 交互

自动躲避

如果 FAB 是 CoordinatorLayout 的子项,它会自动“躲避”弹出的 Snackbar,防止被遮挡。此外,当关联的 AppBarLayout 折叠时,它也会自动隐藏。