ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
# 1. 前言 按照`Material Design`的理念,应用程序的界面不仅仅是一个平面,而应该是有立体效果的。在官方给出的示例中,最简单且最具代表性的立面设计就是悬浮按钮了。`FloatingActionButton`(简称,`FAB`)是`Material`库中提供的一个控件,这个控件可以帮助我们比较轻松地实现悬浮按钮的效果。它默认会使用`colorAccent`作为按钮的颜色。 # 2. 使用 直接在`TestActivity`的布局文件中引入: ~~~ <?xml version="1.0" encoding="utf-8"?> <!--如果要使用FAB,那么就需要使用androidx.coordinatorlayout.widget.CoordinatorLayout包裹起来--> <androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:orientation="vertical"> <!--引入下拉刷新控件--> <androidx.swiperefreshlayout.widget.SwipeRefreshLayout android:id="@+id/swiperefreshLayout" android:layout_width="match_parent" android:layout_height="match_parent" > <!-- 将内容包裹起来 --> <TextView android:layout_width="wrap_content" android:layout_height="?attr/actionBarSize" android:text="测试下拉刷新" /> </androidx.swiperefreshlayout.widget.SwipeRefreshLayout> <!--这里使用FAB悬浮按钮--> <com.google.android.material.floatingactionbutton.FloatingActionButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_baseline_add_24" app:elevation="8dp" android:layout_gravity="bottom|end" android:layout_margin="16dp" /> </androidx.coordinatorlayout.widget.CoordinatorLayout> ~~~ 需要注意的是,如果不使用`CoordinatorLayout`包裹起来,`FAB`不会显示。 效果: ![](https://img.kancloud.cn/49/4e/494e840928084f7351f11468e8d9e3e2_326x501.png) 至于如何进行事件处理,`FAB`和普通的`Button`其实没什么两样,都是调用`setOnClickListener()`方法来设置按钮的点击事件,这里就不再演示。 # 3. 修改颜色 可以在`xml`中直接修改: ~~~ <!--FAB悬浮按钮--> <com.google.android.material.floatingactionbutton.FloatingActionButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|end" android:layout_marginEnd="16dp" android:layout_marginBottom="76dp" android:src="@drawable/ic_baseline_add_24" app:backgroundTint="@color/white" app:elevation="8dp" /> ~~~ 使用`app:backgroundTint`属性指定即可。 效果: ![](https://img.kancloud.cn/0d/1e/0d1ec104384706d4897faf7724ea8208_394x232.png)