华域联盟 Andriod RecyclerView索引溢出异常的解决方法

RecyclerView索引溢出异常的解决方法

使用RecyclerView过程中遇到异常:

java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder

继承并重写LinearLayoutManager.onLayoutChildren()方法

class WrappedLinearLayoutManager : 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: RecyclerView.Recycler?, state: RecyclerView.State) {
    try {
      super.onLayoutChildren(recycler, state)
    } catch (e: IndexOutOfBoundsException) {
      e.printStackTrace()
    }
  }
}

调用时使用WrappedLinearLayoutManager代替LinearLayoutManager

val recyclerAdapter = RecyclerViewAdapter(activity)
val manager = WrapContentLinearLayoutManager(context).apply { orientation = LinearLayoutManager.VERTICAL }

val recyclerView = view.findViewById<RecyclerView>(R.id.recycler_view).apply {
  layoutManager = manager
  adapter = recyclerAdapter
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持华域联盟。

本文由 华域联盟 原创撰写:华域联盟 » RecyclerView索引溢出异常的解决方法

转载请保留出处和原文链接:https://www.cnhackhy.com/106387.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

Dagger2新手入门与使用基础教程

Android实现键盘弹出界面上移的实现思路

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们