如何使用Kotlin确定Android中RecyclerView的滚动速度?

eit6fx6z  于 2023-06-04  发布在  Android
关注(0)|答案(1)|浏览(275)

我想计算recyclerview的滚动速度。我想通过了解用户是否快速向下滚动页面来执行某些操作。
我在StackOverflow上找到了这个代码块。我想这段代码是用来改变滚动速度的。我不想改变,只想计算速度,并根据这个速度执行一些事情。

class CustomLinearLayoutManager : LinearLayoutManager {
    constructor(context: Context?) : super(context) {}
    constructor(context: Context?, orientation: Int, reverseLayout: Boolean) : super(
        context,
        orientation,
        reverseLayout
    ) {
    }

    constructor(
        context: Context?,
        attrs: AttributeSet?,
        defStyleAttr: Int,
        defStyleRes: Int
    ) : super(context, attrs, defStyleAttr, defStyleRes) {
    }

    companion object {
        private const val MILLISECONDS_PER_INCH = 5f //default is 25f (bigger = slower)
    }

    override fun smoothScrollToPosition(
        recyclerView: RecyclerView,
        state: RecyclerView.State?,
        position: Int
    ) {
        val linearSmoothScroller: LinearSmoothScroller =
            object : LinearSmoothScroller(recyclerView.context) {
                override fun computeScrollVectorForPosition(targetPosition: Int): PointF? {
                    return super.computeScrollVectorForPosition(targetPosition)
                }

                protected override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics): Float {
                    return MILLISECONDS_PER_INCH / displayMetrics.densityDpi
                }
            }
        linearSmoothScroller.setTargetPosition(position)
        startSmoothScroll(linearSmoothScroller)
    }
}
von4xj4u

von4xj4u1#

private var lastScrollTime: Long = 0
private var lastScrollY: Int = 0
private var scrollSpeed: Int = 0

recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
    override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
        super.onScrollStateChanged(recyclerView, newState)
        if (newState == RecyclerView.SCROLL_STATE_IDLE) {
            val currentTime = System.currentTimeMillis()
            val timeDelta = currentTime - lastScrollTime
            val distanceDelta = recyclerView.computeVerticalScrollOffset() - lastScrollY
            scrollSpeed = (distanceDelta / timeDelta * 1000).toInt()
            lastScrollTime = currentTime
            lastScrollY = recyclerView.computeVerticalScrollOffset()
        }
    }

    override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
        super.onScrolled(recyclerView, dx, dy)
        if (recyclerView.scrollState != RecyclerView.SCROLL_STATE_IDLE) {
            lastScrollY = recyclerView.computeVerticalScrollOffset()
        }
    }
})

试试这个
lastScrollTime和lastScrollY分别记录最后滚动停止的时间戳和滚动距离。在onScrollStateChanged方法中,如果滚动停止,则计算滚动时间和距离以获得滚动速度。在onScrolled方法中,如果滚动尚未停止,则更新lastScrollY的值。

相关问题