You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android开发:为RecyclerView实现SwipeRefreshLayout下拉刷新功能

SwipeRefreshLayout下拉刷新逻辑插入位置及实现代码

所有逻辑分两部分插入,不用打乱你已经写好的Retrofit、适配器绑定逻辑:

  • 第一部分:刷新监听初始化,插在MainActivity的onCreate生命周期里,位置在setContentView调用完成、RecyclerView适配器/LayoutManager配置结束之后,接口请求发起之前。
  • 第二部分:刷新状态关闭逻辑,插在你已有的Retrofit拉取列表的请求回调里,成功、失败分支都要加。

核心代码示例

1. onCreate中新增初始化&监听代码

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    // --- 以下是你已经写完的原有逻辑,不用改 ---
    val recyclerView = findViewById<RecyclerView>(R.id.recycler_view)
    val taskAdapter = TaskAdapter()
    recyclerView.layoutManager = LinearLayoutManager(this)
    recyclerView.adapter = taskAdapter
    // --- 原有逻辑结束 ---

    // 👇 就在这个位置加SwipeRefresh相关逻辑,不要挪到接口回调、适配器类里
    val swipeRefreshLayout = findViewById<SwipeRefreshLayout>(R.id.swipe_refresh_layout)
    // 可选:配置刷新动画的配色,和你项目主题对齐就行
    swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_dark, android.R.color.holo_green_dark)
    
    // 绑定下拉刷新监听
    swipeRefreshLayout.setOnRefreshListener {
        // 下拉触发时直接调用你已经封装好的列表拉取方法,不用重复写请求逻辑
        getTaskListFromApi()
    }

    // 可选:首次进入页面自动触发加载,和下拉刷新逻辑复用
    swipeRefreshLayout.isRefreshing = true
    getTaskListFromApi()
}

2. 现有Retrofit请求方法补充状态重置

找到你已经写好的拉取任务列表的方法(比如命名为getTaskListFromApi),在请求的成功、失败回调末尾都加上关闭刷新动画的代码:

private fun getTaskListFromApi() {
    // --- 以下是你已经写完的Retrofit请求逻辑,原有数据绑定代码不用改 ---
    retrofit.create(TaskApi::class.java).getTaskList().enqueue(object : Callback<List<Task>> {
        override fun onResponse(call: Call<List<Task>>, response: Response<List<Task>>) {
            if (response.isSuccessful) {
                taskAdapter.submitList(response.body())
            }
            // 👇 新增:请求成功后关闭刷新动画
            swipeRefreshLayout.isRefreshing = false
        }

        override fun onFailure(call: Call<List<Task>>, t: Throwable) {
            Toast.makeText(this@MainActivity, "网络异常,加载失败", Toast.LENGTH_SHORT).show()
            // 👇 新增:请求失败也要关闭刷新动画,避免动画一直转
            swipeRefreshLayout.isRefreshing = false
        }
    })
}

常见踩坑点

  • 不要把setOnRefreshListener写在Retrofit的请求回调里,会导致首次进入页面时下拉无反应,必须等第一次请求完成才能触发刷新
  • 布局里SwipeRefreshLayout只能有一个直接子View,就是你的RecyclerView,中间不要嵌套NestedScrollView、其他LinearLayout之类的布局,否则会出现下拉冲突
  • 不要在刷新监听里重复初始化RecyclerView、适配器实例,会导致列表位置重置、内存泄漏
  • 如果用了ListAdapter做数据差分更新,直接调用submitList即可,不用额外调用notifyDataSetChanged

内容的提问来源于stack exchange,提问作者user19437536

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 05:57:11