Created
June 19, 2018 10:16
-
-
Save bhargavms/1fddf07ae8acbbae973cfdeadadcbbcf to your computer and use it in GitHub Desktop.
Accurate vertical scroll offset computation for LinearLayoutManager
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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