Created
February 4, 2025 14:28
-
-
Save yoonseopshin/b32a2824aa17e9d698394c8eb2649e5e to your computer and use it in GitHub Desktop.
Sample for RecyclerView smooth scroll animation speed and offset.
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 CustomSpeedLinearLayoutManager( | |
context: Context, | |
private val offsetProvider: (position: Int) -> Int | |
) : LinearLayoutManager(context) { | |
override fun smoothScrollToPosition(recyclerView: RecyclerView, state: RecyclerView.State, position: Int) { | |
val viewHolder = recyclerView.findViewHolderForAdapterPosition(position)?.itemView | |
val itemHeight = viewHolder?.height ?: 0 | |
// just sample value, speed up if viewholder's height is long enough. | |
val speedRatio = when { | |
itemHeight <= 1000 -> 1.0f | |
itemHeight <= 2000 -> 2.0f | |
else -> 3.0f | |
} | |
val smoothScroller = object : LinearSmoothScroller(recyclerView.context) { | |
override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics): Float { | |
return super.calculateSpeedPerPixel(displayMetrics) / speedRatio | |
} | |
override fun calculateDyToMakeVisible(view: View?, snapPreference: Int): Int { | |
return super.calculateDyToMakeVisible(view, snapPreference) - offsetProvider(position) | |
} | |
} | |
smoothScroller.targetPosition = position | |
startSmoothScroll(smoothScroller) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment