前言:当数据量比较大(如200条以上)明显感觉到APP卡顿,通过排查发现是RecycleView适配器的onBindViewHolder有多少条数据就执行多少次,滑动显示懒加载失效了。
原因:RecycleView或父控件在水平方向使用android:layout_weight="1"属性则会导致RecycleView懒加载无效
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rv_test"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"/>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"/>
</LinearLayout>
class TestAdapter : RecyclerView.Adapter<TestAdapter.TestViewHolder>(){
private val testList = arrayListOf<String>()
init {
for (i in 1..500){
testList.add("第{$i}项")
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TestViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_test, parent, false)
return TestViewHolder(view)
}
override fun getItemCount(): Int {
return testList.size
}
override fun onBindViewHolder(holder: TestViewHolder, position: Int) {
holder.tvItem.text = testList[position]
Log.e("aa", "***********$position")
}
class TestViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val tvItem = view.findViewById<TextView>(R.id.tv_item)
}
}
rv_test.layoutManager = LinearLayoutManager(this)
rv_test.adapter = TestAdapter()
方案:对于RecycleView在水平方向需要百分比,不要采用“LinearLayout + layout_weight”方案,可以使用“ConstraintLayout+layout_constraintWidth_percent”代替
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rv_test"
android:layout_width="0dp"
android:layout_height="match_parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintWidth_percent="0.5"/>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
app:layout_constraintStart_toEndOf="@+id/rv_test"
app:layout_constraintEnd_toEndOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
最后:还有另一种失效情况《RecycleView懒加载失效问题(二)》