使用RecyclerView适配器更新数据的最佳方法 [英] Best way to update data with a RecyclerView adapter

查看:1342
本文介绍了使用RecyclerView适配器更新数据的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我必须将经典适配器与 ListView 一起使用时,我会更新ListView中的数据是这样的:

When I have to use a classic adapter with a ListView, I update my data in the ListView like this:

myAdapter.swapArray(data);

public swapArray(List<Data> data) {
  clear();
  addAll(data);
  notifyDataSetChanged();
}

我想知道 RecyclerView 的最佳做法是什么.因为在 RecyclerView 适配器中,您不能像在 ListView 中那样执行clearaddAll.

I would like to know what is the best practice for a RecyclerView. Because in a RecyclerView adapter you can't do a clear and addAll as in ListView.

所以我只尝试了notifyDataSetChanged,但是没有用. 然后我在视图上尝试了swapAdapter:

So I tried just with a notifyDataSetChanged, but it didn't work. Then I tried with a swapAdapter on my view:

List<Data> data = newData;

MyRecyclerAdapter adapter = new MyRecyclerAdapter(data);

// swapAdapter on my recyclerView (instead of a .setAdapter like with a classic listView).
recyclerViewList.swapAdapter(adapter, false);

但是使用最后一个解决方案,我仍然必须创建适配器的新实例,我觉得这不是最佳解决方案.我应该可以只更改数据而无需新的MyRecyclerAdapter.

But with this last solution, I still have to create a new instance of my adapter and I feel like it's not the best solution. I should be able just to change my data without a new MyRecyclerAdapter.

推荐答案

RecyclerView的适配器没有ListView的适配器中提供的许多方法.但是您的交换可以非常简单地实现为:

RecyclerView's Adapter doesn't come with many methods otherwise available in ListView's adapter. But your swap can be implemented quite simply as:

class MyRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
   List<Data> data;
   ...

    public void swap(ArrayList<Data> datas)
    {
        data.clear();
        data.addAll(datas);
        notifyDataSetChanged();     
    }
}

list.clear();
list.add(data);

list = newList;

第一个是重用相同的列表对象.另一个是取消引用和引用列表.无法再访问的旧列表对象将被垃圾回收,但必须先堆积堆内存.这将与您每次要交换数据时初始化新适配器的过程相同.

The first is reusing the same list object. The other is dereferencing and referencing the list. The old list object which can no longer be reached will be garbage collected but not without first piling up heap memory. This would be the same as initializing new adapter everytime you want to swap data.

这篇关于使用RecyclerView适配器更新数据的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆