android 更新适配器,android - 使用RecyclerView适配器更新数据的最佳方法

android - 使用RecyclerView适配器更新数据的最佳方法

这个问题在这里已有答案:

如何更新RecyclerView适配器数据?                                     12个答案

当我必须使用带有ListView的经典适配器时,我在ListView中更新我的数据,如下所示:

myAdapter.swapArray(data);

public swapArray(List data) {

clear();

addAll(data);

notifyDataSetChanged();

}

我想知道RecyclerView的最佳实践是什么。 因为在RecyclerView适配器中,您不能像在ListView中那样执行MyRecyclerAdapter和addAll。

所以我尝试使用MyRecyclerAdapter,但它没有用。然后我尝试在我的视图上使用swapAdapter:

List 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的情况下更改我的数据。

4个解决方案

98 votes

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

class MyRecyclerAdapter extends RecyclerView.Adapter {

List data;

...

public void swap(ArrayList datas)

{

if(datas == null || datas.size()==0)

return;

if (data != null && data.size()>0)

data.clear();

data.addAll(datas);

notifyDataSetChanged();

}

}

还有一个区别

list.clear();

list.add(data);

list = newList;

第一个是重用相同的列表对象。 另一种是解除引用和引用列表。 无法再访问的旧列表对象将被垃圾收集,但不是没有首先堆积堆内存。 这与每次要交换数据时初始化新适配器相同。

inmyth answered 2019-06-13T06:57:56Z

20 votes

@ inmyth的答案是正确的,只需修改一下代码,就可以处理空列表了。

public class NewsAdapter extends RecyclerView.Adapter<...> {

...

private static List mFeedsList;

...

public void swap(List list){

if (mFeedsList != null) {

mFeedsList.clear();

mFeedsList.addAll(list);

}

else {

mFeedsList = list;

}

notifyDataSetChanged();

}

我正在使用Retrofit来获取列表,在Retrofit的onResponse()上使用,

adapter.swap(feedList);

Akshay Goyal answered 2019-06-13T06:58:35Z

10 votes

DiffUtil是更新您在android框架中可以找到的RecyclerView Adapter中的数据的最佳选择。 DiffUtil是一个实用程序类,可以计算两个列表之间的差异,并输出将第一个列表转换为第二个列表的更新操作列表。

大多数情况下,我们的列表完全更改,我们将新列表设置为RecyclerView Adapter。 我们调用notifyDataSetChanged来更新适配器。 NotifyDataSetChanged成本很高。 DiffUtil类现在解决了这个问题。 它完美地完成了它的工作!

Ngima Sherpa answered 2019-06-13T06:59:10Z

3 votes

找到以下解决方案为我的类似问题工作:

private ExtendedHashMap mData = new ExtendedHashMap();

private String[] mKeys;

public void setNewData(ExtendedHashMap data) {

mData.putAll(data);

mKeys = data.keySet().toArray(new String[data.size()]);

notifyDataSetChanged();

}

使用clear-command

mData.clear()

没有必要

termigrator answered 2019-06-13T06:59:52Z

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值