Floating action button (FAB) 是一个带有环状阴影的圆形按键,位于 UI 之上,用于显示常用的操作,比如添加新条目、编写邮件等。
Android Reference 文档中关于 FloatingActionButton 的部分指出,floating button 有两种大小可选:1、普通(56dp);2、迷你(40dp)。
1
2
3
4
5
6
7
8
9
|
final int getSizeDimension() {
switch
(
this
.mSize) {
case
0:
default
:
return
this
.getResources().getDimensionPixelSize(dimen.fab_size_normal);
case
1:
return
this
.getResources().getDimensionPixelSize(dimen.fab_size_mini);
}
}
|
注意 :
FloatingActionButton 只是一个扩展于 ImageView 的 view。
添加 Android design support library
首先,在 gradle 文件中添加如下一行以添加 Android support library:
1
|
compile
'com.android.support:design:22.2.0'
|
Step 1
在 xml 布局文件中添加 FloatingActionButton。此处假设以下
<android.support.design.widget.FloatingActionButton
android:id=
"@+id/btnFloatingAction"
android:layout_width=
"wrap_content"
android:layout_height=
"wrap_content"
android:layout_gravity=
"bottom|right"
/>
属性介绍:
-
FAB 默认使用应用主题中设置的浮起色作为按键背景。你可以使用 app:backgroundTint 属性,或者调用 setBackgroundTintList (ColorStateList tint) 方法改变 FAB 背景色;
-
如上文中提到的,可以使用 app:fabSize 属性选择普通大小或者迷你大小;
-
使用 android:src 改变 FAB 对应的 drawable;
-
使用 app:rippleColor 设置 FAB 按下时的波纹效果;
-
使用 app:borderWidth 设置 FAB 边框宽度;
-
使用 app:elevation 设置闲置状态下 FAB 的景深(默认是 6dp);
-
使用 app:pressedTranslationZ 设置 FAB 按下时的景深(默认是 12dp)。
Step 2
添加以下代码,用以显示带有图片和大小属性的 FAB。
1
2
3
4
5
6
7
8
|
<android.support.design.widget.FloatingActionButton
android:id=
"@+id/btnFloatingAction"
android:layout_width=
"wrap_content"
android:layout_height=
"wrap_content"
android:layout_gravity=
"bottom|right"
android:src=
"@drawable/ic_plus"
app:fabSize=
"normal"
app:rippleColor=
"@android:color/background_dark"
/>
|
Step 3
采用与 ImageView 或 Button 相同的方法,为 FAB 添加点击事件。
1
2
3
4
5
6
7
8
|
FloatingActionButton btnFab = (FloatingActionButton) findViewById(R.id.btnFloatingAction);
btnFab.setOnClickListener(
new
View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.
this
,
"Hello FAB!"
, Toast.LENGTH_SHORT).show();
}
});
|
Issues:
本文编写时,FAB 支持库仍然存在一些 bug,在 Kitkat 和 Lollipop 中分别运行示例代码,可以看到如下结果:
Lollipop 中的 FAB:
Kitkat 中的 FAB:
Issues 1: Android 4.4 和 5.0 中边缘显示
很容易看出,Lollipop 中存在边缘显示的问题。为了解决此问题,API21+ 的版本统一定义底部与右边缘空白为 16dp,Lollipop 以下版本统一设置为 0dp.
values/dimens.xml
1
2
|
<dimen name=
"fab_margin_right"
>0dp</dimen>
<dimen name=
"fab_margin_bottom"
>0dp</dimen>
|
values-v21/dimens.xml
1
2
|
<dimen name=
"fab_margin_right"
>16dp</dimen>
<dimen name=
"fab_margin_bottom"
>16dp</dimen>
|
布局文件的 FAB 中,也设置相应的值。
1
2
3
4
5
|
<android.support.design.widget.FloatingActionButton
...
...
android:layout_marginBottom=
"@dimen/fab_margin_bottom"
android:layout_marginRight=
"@dimen/fab_margin_right"
/>
|
Issues 2: Android 5.0 中阴影显示
再看一遍上面的截图,会发现 Kitkat 中有阴影显示,而 Lollipop 中并没有。在 Lollipop 上,可以直接在 FAB 中设置:
1
2
3
4
5
6
7
|
<android.support.design.widget.FloatingActionButton
...
...
app:fabSize=
"normal"
app:borderWidth=
"0dp"
android:layout_marginBottom=
"@dimen/fab_margin_bottom"
android:layout_marginRight=
"@dimen/fab_margin_right"
/>
|
Issues 3: FAB 中没有旋转动画