Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bhargavms/1fddf07ae8acbbae973cfdeadadcbbcf to your computer and use it in GitHub Desktop.
Save bhargavms/1fddf07ae8acbbae973cfdeadadcbbcf to your computer and use it in GitHub Desktop.
Accurate vertical scroll offset computation for LinearLayoutManager
class LinearLayoutManagerWithAccurateOffset(context: Context?) : LinearLayoutManager(context) {
// map of child adapter position to its height.
private val childSizesMap = mutableMapOf<Int, Int>()
override fun onLayoutCompleted(state: RecyclerView.State?) {
super.onLayoutCompleted(state)
for (i in 0 until childCount) {
val child = getChildAt(i)
childSizesMap[getPosition(child)] = child.height
}
}
override fun computeVerticalScrollOffset(state: RecyclerView.State?): Int {
if (childCount == 0) {
return 0
}
val firstChildPosition = findFirstVisibleItemPosition()
val firstChild = findViewByPosition(firstChildPosition)
var scrolledY: Int = -firstChild.y.toInt()
for (i in 0 until firstChildPosition) {
scrolledY += childSizesMap[i] ?: 0
}
return scrolledY
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment