Android随手记-Inconsistency detected. Invalid item position

  • RecyclerView 的 Inconsistency detected. Invalid item position 错误

  • 资料来源:

    https://stackoverflow.com/questions/30220771/recyclerview-inconsistency-detected-invalid-item-position
    https://juejin.im/entry/5a965c8b5188257a84626928

  • 更新

    1
    20.07.07 初始化

问题

遇到个非常奇怪的bug

  • 搜索特定字词会 fc
  • Log: Inconsistency detected. Invalid item position,但并没有提示代码错误.
  • 但是触发条件一定是初次进入界面,在界面内只要有上下滑动,再搜索字词就会没事.

解决

依照搜索的描述,似乎是 RecyclerView 实际的列表集合与 Adapter 的列表集合不一致,是 Google 的锅.这…

网上提到的其他解决方式是对 Adapter 改造,适时调用 notifyItemRangeXXX,以保持数据集合的一致性.但是 Nowakelock 把这部分托管给 Listadapter 了,以上无效.

那来最直接的吧,覆写 LinearLauoutManager 捕获这个错误.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class WrapContentLinearLayoutManager : LinearLayoutManager {
constructor(context: Context?) : super(context)
constructor(context: Context?, orientation: Int, reverseLayout: Boolean) : super(
context,
orientation,
reverseLayout
)

constructor(
context: Context?,
attrs: AttributeSet?,
defStyleAttr: Int,
defStyleRes: Int
) : super(context, attrs, defStyleAttr, defStyleRes)

override fun onLayoutChildren(
recycler: Recycler,
state: RecyclerView.State
) {
try {
super.onLayoutChildren(recycler, state)
} catch (e: IndexOutOfBoundsException) {
LogUtil.d("test2", "$e")
e.printStackTrace()
}
}
}

app:layoutManager="com.js.nowakelock.ui.databding.WrapContentLinearLayoutManager"