Skip to content

Instantly share code, notes, and snippets.

@SurajBahadur
Created September 20, 2022 08:01
Show Gist options
  • Save SurajBahadur/fcec9defa90c49a6f6a3afe63368136c to your computer and use it in GitHub Desktop.
Save SurajBahadur/fcec9defa90c49a6f6a3afe63368136c to your computer and use it in GitHub Desktop.
Smooth Scroll To any position via skipping middle item list in RecyclerView Android
private fun smoothScroll(currentPosition: Int, newPosition: Int) {
Log.d("new_position", "$newPosition")
if (newPosition > currentPosition) {
//scroll top to bottom
binding.upperRecycler.scrollToPosition(newPosition - 2)
binding.upperRecycler.smoothSnapToPosition(newPosition - 1) {
//Reason for adding this is that if RecyclerView height is 0dp or match parent OR more than one items visible on the
// screen then instead of focus on passed position, it scroll down/up depend
binding.upperRecycler.scrollBy(0, -250)
}
} else if (newPosition < currentPosition) {
// scroll bottom to top
binding.upperRecycler.scrollToPosition(newPosition)
binding.upperRecycler.smoothSnapToPosition(newPosition - 1) {
binding.upperRecycler.scrollBy(0, -250)
}
}
}
//Create an extension
fun RecyclerView.smoothSnapToPosition(position: Int, snapMode: Int = LinearSmoothScroller.SNAP_TO_START, listener: (String) -> Unit) {
val scrollDuration = 200000f
val smoothScroller = object : LinearSmoothScroller(this.context) {
override fun getVerticalSnapPreference(): Int = snapMode
override fun getHorizontalSnapPreference(): Int = snapMode
override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics?): Float {
return scrollDuration / computeVerticalScrollRange()
}
override fun onStop() {
super.onStop()
listener("onStop")
}
}
smoothScroller.targetPosition = position
layoutManager?.startSmoothScroll(smoothScroller)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment