首页 > 解决方案 > Recyclerview 刷新项目甚至无需调用 notifyDataSetChanged()

问题描述

让我解释一下发生了什么。我有一个片段,在它的 onCreateView() 中我将适配器设置为 recyclerview 没有任何项目..

 @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        downloadsList = new ArrayList<>();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
        downloadsRecyclerview.setLayoutManager(linearLayoutManager);
        downloadsList.clear();
        downloadAdapter = new DownloadAdapter(context, downloadsList);
        downloadsRecyclerview.setAdapter(downloadAdapter);
       }

现在奇怪的部分是每当我将项目添加到downloadsList(基本上是一个 ArrayList )时,我的 recyclerview 就会使用 downloadsList 上可用的内容进行更新。我什至没有调用 notifyDataSetChanged() 或再次设置新适配器...任何帮助..

标签: androidandroid-fragmentsandroid-recyclerview

解决方案


如果您不想重新加载整个RecyclerView使用notifyDataSetChanged()然后简单添加notifyItemInserted()

当您添加价值时downloadsList,只需调用

downloadAdapter.notifyItemInserted(downloadsList.size()-1)

推荐阅读