使用 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 那样执行 clear
和 addAll
.
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.