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

Android RecyclerView调用notify系列方法不生效,加载更多数据不显示

问题根因定位
  • 核心错误:每次接口请求完成后都会新创建一个NotificationAdapter实例,只有page=1时会将新实例绑定到RecyclerView,page>1时调用updateList的是未绑定到RecyclerView的新实例,实际和RecyclerView绑定的旧Adapter从未收到数据更新,自然不会刷新UI。
  • 辅助排查点:需确认RecyclerView是否正确设置了LayoutManager,以及item布局的根布局高度未误用match_parent(否则单item占满全屏,会误以为新数据未加载)。
修复方案

1. 调整Adapter实例化逻辑

将Adapter改为页面全局成员变量,仅在页面初始化时实例化1次,不要每次接口请求都新建:

// 页面全局声明Adapter
private NotificationAdapter adapter;
// 全局保存全量数据列表
private List<NotificationDataItem> allDataList = new ArrayList<>();

// 在onViewCreated/onCreate等初始化方法中提前初始化Adapter
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    // 初始化时传入空列表,后续接口请求再更新数据
    adapter = new NotificationAdapter(requireActivity(), allDataList);
    // 提前给RecyclerView设置Adapter和LayoutManager
    binding.rvNotification.setLayoutManager(new LinearLayoutManager(requireContext()));
    binding.rvNotification.setAdapter(adapter);
}

2. 调整接口请求后的分页更新逻辑

删除每次请求都新建Adapter的代码,分别处理第一页和分页的更新逻辑:

List<NotificationDataItem> newData = response.body().getData().getData();
if (page == 1) {
    // 第一页/下拉刷新:替换全量数据
    allDataList.clear();
    allDataList.addAll(newData);
    adapter.notifyDataSetChanged();
} else {
    // 分页加载:追加数据,使用范围刷新性能更高
    int oldSize = allDataList.size();
    allDataList.addAll(newData);
    adapter.notifyItemRangeInserted(oldSize, newData.size());
}

3. 可选优化Adapter更新方法

也可以把数据更新逻辑封装到Adapter内部,避免外部直接操作数据源,可删除原有updateList方法:

// Adapter内新增替换全量数据方法
public void setList(List<NotificationDataItem> newData) {
    this.mData.clear();
    this.mData.addAll(newData);
    notifyDataSetChanged();
}

// Adapter内新增追加数据方法
public void addList(List<NotificationDataItem> newData) {
    int oldSize = this.mData.size();
    this.mData.addAll(newData);
    notifyItemRangeInserted(oldSize, newData.size());
}

封装后接口请求处的逻辑可以简化为:

List<NotificationDataItem> newData = response.body().getData().getData();
if (page == 1) {
    adapter.setList(newData);
} else {
    adapter.addList(newData);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 04:15:03