Skip to content

Instantly share code, notes, and snippets.

@snowpero
Created February 14, 2025 09:13
Show Gist options
  • Save snowpero/0965f3deb09a83dfc2488ede1e2fa6f0 to your computer and use it in GitHub Desktop.
Save snowpero/0965f3deb09a83dfc2488ede1e2fa6f0 to your computer and use it in GitHub Desktop.
smoothScrollToPositionWithOffset.kt
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