如何完全采用RecyclerView的SortedList

Kir*_*man 5 java android kotlin android-support-library android-recyclerview

RecyclerView库最近添加了新SortedList类.假设我有一个回调,它实现了一个compare()可以随时间变化的方法,即可以切换底层的Comparator.告诉SortedList完全使用其数据的最佳方法是什么?

Kir*_*man 2

这是我自己的看法(用 Kotlin 编写):

list.beginBatchedUpdates()

val indices = (0..list.size() - 1).toArrayList()

while (!indices.isEmpty()) {
    val i = indices.first()
    val item = list.get(i)

    list.recalculatePositionOfItemAt(i)

    [suppress("USELESS_CAST_STATIC_ASSERT_IS_FINE")]
    indices.remove(list.indexOf(item) as Any) //cast to disambiguate remove()
}

list.endBatchedUpdates()
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我在每次调用后跟踪新索引,recalculatePositionOfItemAt()因此每个项目仅使用一次,并且不会跳过任何项目。

这可行,但看起来确实很浪费,因为recalculatePositionOfItemAt()将调整底层数组的大小两次以删除然后重新添加该项目。indexOf即使索引已知,也会执行新的二分搜索。

编辑:如果项目比较相等,这似乎会导致无限循环。

替代方法(删除全部,然后添加全部):

list.beginBatchedUpdates()

val copy = (list.size() - 1 downTo 0).map { list.removeItemAt(it) }
copy.forEach { list.add(it) }

list.endBatchedUpdates()
Run Code Online (Sandbox Code Playgroud)