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

Android开发中SwipeRefreshLayout下拉刷新不生效问题求助

问题原因
  • 布局属性配置错误:SwipeRefreshLayout的子控件RecyclerView宽高均设置为0dp,SwipeRefreshLayout无法正确识别子控件的滚动状态,直接导致下拉手势无法响应。
  • 刷新逻辑存在缺失:OnRefreshListener回调中仅调用了适配器的刷新方法,没有重新执行Firestore数据拉取逻辑,列表数据不会更新;且回调中直接同步调用setRefreshing(false),甚至不会显示下拉刷新的加载动画,看起来像功能完全失效。
解决方案

1. 修改XML布局

将RecyclerView的宽高属性改为match_parent,SwipeRefreshLayout本身的约束布局0dp配置无需修改:

<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
    android:id="@+id/swipeRefreshLayout"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/searchCardView">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="8dp"
        tools:listitem="@layout/room_dashboard_sample"/>

</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

2. 重构业务逻辑

将Firestore数据拉取逻辑封装为公共方法,在下拉刷新回调中触发重新拉取,数据加载完成后再关闭刷新状态:

// 封装公共的数据加载方法
private void loadRoomsData(){
    modelList.clear();
    firestore.collection("Rooms").orderBy("timestamp", Query.Direction.DESCENDING).get()
        .addOnSuccessListener(queryDocumentSnapshots -> {
            List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();
            for (DocumentSnapshot d : list) {
                DashboardModel obj = d.toObject(DashboardModel.class);
                modelList.add(obj);
            }
            dashboardAdapter.notifyDataSetChanged();
            // 数据加载成功后关闭刷新状态
            if(binding.swipeRefreshLayout.isRefreshing()){
                binding.swipeRefreshLayout.setRefreshing(false);
            }
        })
        .addOnFailureListener(e -> {
            Timber.d("onFailure: %s", e.getMessage());
            // 加载失败也需要关闭刷新状态,避免动画一直展示
            if(binding.swipeRefreshLayout.isRefreshing()){
                binding.swipeRefreshLayout.setRefreshing(false);
            }
        });
}

修改初始化和刷新监听的代码:

// 初始化逻辑
modelList = new ArrayList<>();
dashboardAdapter = new DashboardAdapter(this, modelList);
binding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
binding.recyclerView.setAdapter(dashboardAdapter);
// 页面首次加载调用数据拉取方法
loadRoomsData();

// 修改刷新监听逻辑
binding.swipeRefreshLayout.setOnRefreshListener(() -> {
    // 下拉时触发重新拉取数据
    loadRoomsData();
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 16:48:02