ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
# 1. 前言 `SwipeRefreshLayout`就是用于实现下拉刷新功能的核心类,我们把想要实现下拉刷新功能的控件放置到`SwipeRefreshLayout`中,就可以迅速让这个控件支持下拉刷新。 # 2. 使用 需要添加一下依赖: ~~~ implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0' ~~~ 然后在`xml`文件中将要下拉刷新的包裹起来: ~~~ <?xml version="1.0" encoding="utf-8"?> <LinearLayout 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" android:orientation="vertical" tools:context=".MainActivity"> <!--引入下拉刷新控件--> <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> </LinearLayout> ~~~ 然后,我们需要在代码中处理具体的刷新逻辑: ~~~ class TestActivity : AppCompatActivity() { // 找到下拉刷新控件 val swiperefreshLayout by lazy { findViewById<SwipeRefreshLayout>(R.id.swiperefreshLayout) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_test) // 设置下拉刷新的圆圈的颜色 swiperefreshLayout.setColorSchemeResources(R.color.purple_700) // 模拟数据耗时请求 swiperefreshLayout.setOnRefreshListener { refershData() } } fun refershData(){ // 模拟请求,耗时两秒结束 thread { Thread.sleep(2000) runOnUiThread { // 设置停止下拉刷新 swiperefreshLayout.isRefreshing = false } } } } ~~~ 结果: ![](https://img.kancloud.cn/86/25/8625cdd98b691b06f34fef0eb653a9e1_303x102.png) 下拉刷新旋转两秒消失。