我有无尽的滚动RecyclerView。数据存储在SortedList中。当用户向下滚动时,加载项目会出现,并在加载下10个项目时消失。删除LoaderItem时出现以下错误:
java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position 10(offset:-1).state:11
at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5512)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5448)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5444)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2224)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1551)
at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1511)
at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:595)
at android.support.v7.widget.RecyclerView.dispatchLayoutStep1(RecyclerView.java:3551)
at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:3030)
at android.view.View.measure(View.java)
这是我的代码:
适配器:
val battles = SortedList(RecyclerViewItem::class.java, object : SortedListAdapterCallback<RecyclerViewItem>(this)
{
override fun areItemsTheSame(item1 : RecyclerViewItem?, item2 : RecyclerViewItem?) : Boolean
{
if (item1 is Battle && item2 is Battle && item1.id == item2.id) return true
if (item1 is LoaderItem && item2 is LoaderItem) return true
return false
}
override fun compare(o1 : RecyclerViewItem?, o2 : RecyclerViewItem?) : Int =
if (o1 is Battle && o2 is Battle)
{
when
{
o1.points > o2.points -> 1
o1.points == o2.points -> 0
else -> -1
}
}
else -1
override fun areContentsTheSame(oldItem : RecyclerViewItem?, newItem : RecyclerViewItem?) : Boolean = if (oldItem is LoaderItem) true
else (oldItem as Battle).points == (newItem as Battle).points
})
fun removeLoadingItem()
{
(0 until battles.size()).filter { battles[it] is LoaderItem }.forEach { battles.removeItemAt(it) }
}
fun addDownloadedItems(battles : List<Battle>)
{
this.battles.addAll(battles)
}
片段:
override fun displayDownloadedBattles(battles : List<Battle>, isMore : Boolean) {
pbLoader.visibility = View.GONE
isLoading = false
if (isMore)
adapter.removeLoadingItem()
adapter.addDownloadedItems(battles)
}
答案 0 :(得分:0)
(0 until battles.size()).filter { battles[it] is LoaderItem }.forEach { battles.removeItemAt(it) }
此片段包含错误:首次删除后索引序列不正确。 你可以循环下降。 为什么不使用
battles.filter { it is LoaderItem }.forEach { battles.remove(it) }