Created
February 14, 2025 09:13
-
-
Save snowpero/0965f3deb09a83dfc2488ede1e2fa6f0 to your computer and use it in GitHub Desktop.
smoothScrollToPositionWithOffset.kt
This file contains hidden or 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
private fun RecyclerView.smoothScrollToPositionWithOffset(position: Int, offset: Int) { | |
if (position < 0 || position >= (adapter?.itemCount ?: 0)) return | |
val linearSmoothScroller = object : LinearSmoothScroller(context) { | |
override fun onTargetFound(targetView: View, state: RecyclerView.State, action: Action) { | |
super.onTargetFound(targetView, state, action) | |
val dx = calculateDxToMakeVisible(targetView, horizontalSnapPreference) | |
val dy = calculateDyToMakeVisible(targetView, SNAP_TO_START) | |
val distance = sqrt((dx * dx + dy * dy).toDouble()).toInt() | |
val time = calculateTimeForDeceleration(distance) | |
if (time > 0) { | |
action.update(-dx, -dy - offset, time, mDecelerateInterpolator) | |
} | |
} | |
} | |
linearSmoothScroller.targetPosition = position | |
layoutManager?.startSmoothScroll(linearSmoothScroller) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment