Created
September 20, 2022 08:01
-
-
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
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 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