【问题标题】:Weird behavior of SortedList in RecyclerViewRecyclerView 中 SortedList 的奇怪行为
【发布时间】:2017-10-17 17:42:41
【问题描述】:

我正在使用 SortedList 对某些参数的数据进行排序,比如 RecyclerView 中的“日期”,以便在加载大量数据时提高性能。但我观察到它的非常奇怪的行为。首先让我放一些代码-

mMatchesList = new SortedList<>(Matches.class, new SortedList.Callback<Matches>() {

        @Override
        public int compare(Matches o1, Matches o2) {

            int result = 0;

                try {

                    result = DateTimeOperationUtil.dateComparator("dd-MMM-yyyy", o2.MatchDate, o1.MatchDate);
                } catch (ParseException e) {
                    e.printStackTrace();
                }

            return result;
        }

        @Override
        public void onChanged(int position, int count) {

            notifyItemRangeChanged(position, count);
        }

        @Override
        public boolean areContentsTheSame(Matches oldItem, Matches newItem) {

            return oldItem.equals(newItem);
        }

        @Override
        public boolean areItemsTheSame(Matches item1, Matches item2) {

            return item1.hashCode() == item2.hashCode();
        }

        @Override
        public void onInserted(int position, int count) {

            notifyItemRangeInserted(position, count);
        }

        @Override
        public void onRemoved(int position, int count) {

            notifyItemRangeRemoved(position, count);
        }

        @Override
        public void onMoved(int fromPosition, int toPosition) {

            notifyItemMoved(fromPosition, toPosition);
        }
    });

在这里,我有一些匹配项

我想按日期降序排序

。第一次,订单和我想要的一样,但是

当我更改任何匹配的日期时,应该根据 到定义的顺序。但它没有发生,数据也没有改变 这份名单。

已编辑 我正在使用以下代码更新我的列表:

if (mMatchesList.indexOf(matches) != -1)
        mMatchesList.updateItemAt(mMatchesList.indexOf(matches), matches);

我的 Matches 模型类实现了 equals() 和 hashcode()。

告诉我我做错了什么。

【问题讨论】:

  • 我对SortedList这个类不太熟悉,但是你有没有调用updateItemAt(int index, T item)?
  • @Achez9 是的,我正在调用 updateItemAt(int index, int item) 方法..
  • 您能否发布您如何更新您的对象,以及您如何将该更新分派到 SortedList?

标签: android performance android-recyclerview sortedlist


【解决方案1】:

您没有正确实现areItemsTheSame 方法。您应该检查这两个项目是否相同,即您通过 id(如果数据库模型的主键)或其他可以告诉您两个对象是否相同的方法来检查,而不是 hashCode。两个不同的模型可以有相同的哈希码。

阅读hashCode方法documentation.中的第三个要点

【讨论】:

  • 我尝试将哈希码更改为 Id 比较但没有运气。同样的问题存在..假设我们有三个数据,一个是 10 月 16 日,2 日是 9 月 15 日,3 日是 7 月 3 日,那么如果我尝试将 9 月 15 日更改为低于 7 月 3 日..不更新,但如果我尝试将其更改为大于 10 月 16 日,那么它正在更新..不明白为什么会发生..所有三个日期的年份都相同
  • 更新列表后只需打印列表中的所有元素。这将帮助您缩小错误范围。如果您的列表不代表正确的数据,那么更新部分列表时会出现问题。如果列表代表正确的数据,那么您在 SortedList.Callback 的实现中遇到了问题。
猜你喜欢
  • 2013-10-22
  • 1970-01-01
  • 2015-02-28
  • 2015-03-22
  • 2016-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多