如果我以不同的项目顺序提交相同的列表,则 ListAdapter 不会刷新 RecyclerView [英] ListAdapter not refreshing RecyclerView if I submit the same list with different item order

查看:16
本文介绍了如果我以不同的项目顺序提交相同的列表,则 ListAdapter 不会刷新 RecyclerView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 RecyclerViewListAdapter(使用 AsyncListDiffer 计算和动画替换列表时的更改).

I am using a RecyclerView with ListAdapter (which uses AsyncListDiffer to calculate and animate changes when list is replaced).

问题是,如果我 submit() 一些列表,然后重新排序该列表,然后 submit() 再次,没有任何反应.

The problem is that if I submit() some list, then re-order that list, and submit() again, nothing happens.

我如何强制 ListAdapter 评估这个新列表,即使它相同"(但顺序已更改)?

How do I force ListAdapter to evaluate this new list, even though it is "the same" (but order has changed)?

新发现:

我检查了 submitList() 并且在开始时有一个检查:

I checked source code of submitList() and in the beggining there is a check:

public void submitList(@Nullable final List<T> newList) {
        final int runGeneration = ++this.mMaxScheduledGeneration;
        if (newList != this.mList) {

我认为这就是问题所在.但如何度过呢?我的意思是,开发人员肯定考虑过提交不同的有序列表吗?

I think this is the problem. But how to get past it? I mean, surely the developers thought about submiting a different ordered list?

推荐答案

代替

submitList(mySameOldListThatIModified)

您必须像这样提交一个新列表:

You have to submit a new list like this:

ArrayList newList = new ArrayList(oldList);
newList.add(somethingNew); // Or sort or do whatever you want
submitList(newList);

API 有点问题.我们希望 ListAdapter 保留列表的副本,但它没有,可能是出于内存原因.当您更改旧列表时,您实际上是在更改 ListAdapter 存储的相同列表.当 ListAdapter 检查 if (newList != this.mList) newListmList 都指的是同一个列表实例,因此无论您对该列表进行了哪些更改,它都将等于自身,并忽略您的更新.

It's kind of a problem with the API. We would expect ListAdapter to keep a copy of the list, but it doesn't, probably for memory reasons. When you change your old list, you are actually changing the same list that ListAdapter has stored. When ListAdapter checks if (newList != this.mList) both newList and mList are referring to the same list instance, so no matter what you have changed on that list, it will equal itself, and ignore your update.

在 kotlin 中,您可以通过以下方式创建新列表:

In kotlin you can create a new list via:

val newList = oldList.toMutableList() // Unintuitive way to copy a list
newList[0] = newList[0].copy(isFavourite = false) // Do whatever modifications you want
submitList(newList)

请注意,您不能这样做:

Note that you cannot do this:

newList.first().isFavourite = false

因为这也将更改旧列表中的第一项,并且 ListAdapter 再次不会看到旧列表中的第一项与新列表中的第一项之间的差异.我建议您列表中的所有项目都专门具有 val 属性,以避免出现此问题.

because that will also change the first item in your old list, and again ListAdapter won't see a difference between the first item in your old list and the first item in your new list. I would recommend that all items in your list have val properties exclusively, to avoid this problem.

这篇关于如果我以不同的项目顺序提交相同的列表,则 ListAdapter 不会刷新 RecyclerView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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