I am trying to scroll my RecyclerView
smoothly to certain item position at the initialization of the list and do it so that the item is displayed at the top. To do so I am using LinearSmoothScroller
. But it doesn't work on first use. On first scroll attempt the list just moves to the desired item, without any animation. But when I start my activity with the list again it works great. Here is code from my LayoutManager:
class MyGridLayoutManager(context: Context?, spanCount: Int = 7)
: GridLayoutManager(context, spanCount) {
...
override fun smoothScrollToPosition(recyclerView: RecyclerView?, state: RecyclerView.State?, position: Int) {
val smoothScroller = object : LinearSmoothScroller(recyclerView?.context) {
override fun getVerticalSnapPreference(): Int = LinearSmoothScroller.SNAP_TO_START
override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics?): Float {
return if(displayMetrics == null) super.calculateSpeedPerPixel(displayMetrics)
else 100f / displayMetrics.densityDpi
}
}
smoothScroller.targetPosition = position
startSmoothScroll(smoothScroller)
}
}
Also as you can see I am changing here speed of the scroll and I think that maybe on that first try the scroll isn't instant but somewhat my change to the speed isn't working and it is just very fast? Anyway does any have any idea what is happening and how can I fix my problem with that first, initial smooth scroll?
EDIT:
I've changed the way I am calling the smoothScrollToPosition
. Now I do it like this:
recyclerView.post {
recyclerView.smoothScrollToPosition(position)
}
And it helped. Now on the first attempt it is visible that the list is being scrolled. But it is still way faster than on later list activity launches.
Also while debugging I made sure that scrolling speed in method calculateSpeedPerPixel
is being calculated the same in all cases