1

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

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
matip
  • 794
  • 3
  • 7
  • 27
  • let the views inflate and the arraylist or whatever data list populate then try the scroll I guess – Pemba Tamang Jul 17 '19 at 11:56
  • on second try views are being inflated and list is being populated in the same way, the activity is being created again, and somehow that time scroll is being working fine – matip Jul 17 '19 at 11:58
  • they maybe coming from the cache/Parcel that the os makes or something – Pemba Tamang Jul 17 '19 at 11:59

0 Answers0