android studio用RecyclerView实现下拉刷新功能 并写明代码
时间: 2023-07-12 12:51:23 浏览: 127
好的,以下是实现 RecyclerView 下拉刷新的代码:
首先,在你的项目中添加以下依赖:
```gradle
implementation 'androidx.recyclerview:recyclerview:1.2.0'
implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'
```
接着,在你的布局文件中添加 SwipeRefreshLayout 和 RecyclerView 组件:
```xml
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="@+id/swipe_refresh_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
```
然后,在你的 Activity 或 Fragment 中获取 SwipeRefreshLayout 和 RecyclerView 组件的实例:
```kotlin
private lateinit var swipeRefreshLayout: SwipeRefreshLayout
private lateinit var recyclerView: RecyclerView
swipeRefreshLayout = findViewById(R.id.swipe_refresh_layout)
recyclerView = findViewById(R.id.recycler_view)
```
接下来,创建一个 Adapter,并传入数据,设置给 RecyclerView:
```kotlin
val adapter = MyAdapter(dataList)
recyclerView.adapter = adapter
```
最后,在 SwipeRefreshLayout 中设置下拉刷新的监听事件:
```kotlin
swipeRefreshLayout.setOnRefreshListener {
// 执行下拉刷新的操作
// ...
// 刷新完成后,停止刷新动画
swipeRefreshLayout.isRefreshing = false
}
```
完整的示例代码如下:
```kotlin
class MainActivity : AppCompatActivity() {
private lateinit var swipeRefreshLayout: SwipeRefreshLayout
private lateinit var recyclerView: RecyclerView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
swipeRefreshLayout = findViewById(R.id.swipe_refresh_layout)
recyclerView = findViewById(R.id.recycler_view)
val dataList = mutableListOf<String>()
for (i in 1..20) {
dataList.add("Item $i")
}
recyclerView.layoutManager = LinearLayoutManager(this)
val adapter = MyAdapter(dataList)
recyclerView.adapter = adapter
swipeRefreshLayout.setOnRefreshListener {
// 执行下拉刷新的操作
// ...
// 刷新完成后,停止刷新动画
swipeRefreshLayout.isRefreshing = false
}
}
}
class MyAdapter(private val dataList: List<String>) : RecyclerView.Adapter<MyAdapter.ViewHolder>() {
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val textView: TextView = itemView.findViewById(android.R.id.text1)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(android.R.layout.simple_list_item_1, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.textView.text = dataList[position]
}
override fun getItemCount() = dataList.size
}
```
阅读全文