First, the background of demand generation

In the development of the project, we met a demand of vertical rotation, so we thought of Recycleview to realize it. We set the timer every 3s to slide an item downward, and realized the smooth scrolling by Recycleview’s SmoothScroll. Due to the low height of Item and its sliding speed, the effect was not very good, so I thought of slowing down the sliding speed to solve the problem.

Solve the above problem by LinearSmoothScroller

The code implementation is as follows:

val layoutManager = recycleView.layoutManager as LinearLayoutManager
val targetPosition = layoutManager.findFirstVisibleItemPosition() + 1
val linearSmoothScroller: LinearSmoothScroller = object : LinearSmoothScroller(mallSpecialSaleWidget.context) {
    override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics): Float {
             return 240f / displayMetrics.densityDpi
    }
}
linearSmoothScroller.targetPosition = targetPosition
layoutManager.startSmoothScroll(linearSmoothScroller)
Copy the code

In the LinearSmoothScroller method, the calculateSpeedPerPixel() function returns the time required for each pixel to slide (in milliseconds), so the larger the value is, the slower the slide will be. You can set it according to your actual needs.