仅支持LinearLayoutManager布局的RecyclerView.
class LinearLayoutManagerOffset(context: Context?) : LinearLayoutManager(context) {
private val childSizesMap = mutableMapOf<Int, Int>()
override fun onLayoutCompleted(state: RecyclerView.State?) {
super.onLayoutCompleted(state)
for (i in 0 until childCount) {
getChildAt(i)?.let {
childSizesMap[getPosition(it)] = it.height
}
}
}
override fun computeVerticalScrollOffset(state: RecyclerView.State): Int {
if (childCount == 0) {
return 0
}
val firstChildPosition = findFirstVisibleItemPosition()
val firstChild = findViewByPosition(firstChildPosition)
var scrolledY = (firstChild?.y?.times(-1f)?.toInt()) ?: 0
for (i in 0 until firstChildPosition) {
scrolledY += childSizesMap[i] ?: 0
}
return scrolledY
}
override fun getPosition(view: View): Int {
return (view.layoutParams as? RecyclerView.LayoutParams)?.viewLayoutPosition ?: RecyclerView.NO_POSITION
}
}