RecyclerView 的基本实现参考前篇:https://blog.csdn.net/whjk20/article/details/106950422
现实现 RecyclerView 的下拉刷新, 通过组件SwipeRefreshLayout 实现
目录
2. RecyclerView布局使用SwipeRefreshLayout 包裹
1. 添加SwipeRefreshLayout 组件依赖包
(app 目录build.gradle)
implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.0.0'
2. RecyclerView布局使用SwipeRefreshLayout 包裹
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".SingleTypeViewActivity">
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="@+id/down_pull_update"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
app:cardUseCompatPadding="true"
android:layout_height="match_parent" >
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
</androidx.cardview.widget.CardView>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
3. 设置刷新监听器
private fun downPullRefresh() {
down_pull_update.setOnRefreshListener {
down_pull_update.setProgressBackgroundColorSchemeColor(
context.resources.getColor(
R.color.colorPrimary,
null
)
)
var handler = Handler()
handler.postDelayed({
datas.add(
0,
UserData(
"我是新名字哦",
PIC_IDS[0]
)
)
datas.add(
0,
UserData(
"我也是新名字哦",
PIC_IDS[1]
)
)
baseAdapter.notifyDataSetChanged()
down_pull_update.isRefreshing = false
}, 2000)
}
}
其中设置监听器方法: setOnRefreshListener({}) , 函数体{}为监听刷新的处理。
setProgressBackgroundColorSchemeColor 可以设置进度条背景(可选)。
这里为模拟刷新回调的处理,动态添加了两条数据,在2s后再刷新界面。
主要为以下两个操作,一是通知Adapter数据变化需要更新UI, 二是设置刷新标志位为false以表示刷新结束了
baseAdapter.notifyDataSetChanged()
down_pull_update.isRefreshing = false
至此,下拉刷新已经实现完成。下拉刷新后续再总结