如何使回收站视图仅转到下一个项目?

问题描述 投票:0回答:1

我不会使用

pagerSnapHelper
,因为我遇到了一些问题。我想将
onFling 
侦听器添加到 recyclerView。然后我想传递一个小速度只是为了转到下一个项目,而不是实际的投掷速度。这可能吗?这是什么
mMinFlingVelocity

代码:

 recyclerView.onFlingListener = object : OnFlingListener(){
        override fun onFling(velocityX: Int, velocityY: Int): Boolean {
            Log.d("Tag", "fling")
            recyclerView.fling(0, 1)
            return true
        }

    }
android android-recyclerview
1个回答
1
投票

我正在使用这种方法来避免

SnapHelper

recyclerView.onFlingListener = object : RecyclerView.OnFlingListener(){
                override fun onFling(velocityX: Int, velocityY: Int): Boolean {
                    val minFlingVelocity = ViewConfiguration.get(recyclerView.context).scaledMinimumFlingVelocity
                    if (abs(velocityX) > minFlingVelocity) {
                        val layoutManager = recyclerView.layoutManager as LinearLayoutManager
                        val currentPosition = layoutManager.findFirstVisibleItemPosition()
                        val nextPosition = if (velocityX > 0) currentPosition + 1 else currentPosition - 1

                        val itemCount = recyclerView.adapter?.itemCount ?: 0
                        if (nextPosition in 0 until itemCount) {
                            recyclerView.smoothScrollToPosition(nextPosition)
                            return true
                        }
                    }
                    return false
                }
            }

我在做:

  1. 根据当前滚动位置和速度计算下一项的位置
  2. 检查下一个位置是否在适配器范围内
  3. 顺利滚动到下一个位置

让我知道它是否适合你。

编辑

创建自定义 LinearSmoothScroller

class CustomLinearSmoothScroller(context: Context) : LinearSmoothScroller(context) {

    override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics): Float {
        val minFlingVelocity = ViewConfiguration.get(context).scaledMinimumFlingVelocity
        return minFlingVelocity.toFloat() / displayMetrics.densityDpi
    }

}

然后添加到

onFligListener

recyclerView.onFlingListener = object : OnFlingListener(){
    override fun onFling(velocityX: Int, velocityY: Int): Boolean {
        val minFlingVelocity = ViewConfiguration.get(recyclerView.context).scaledMinimumFlingVelocity
        if (abs(velocityX) > minFlingVelocity) {
            val layoutManager = recyclerView.layoutManager as LinearLayoutManager
            val currentPosition = layoutManager.findFirstVisibleItemPosition()
            val nextPosition = if (velocityX > 0) currentPosition + 1 else currentPosition - 1

            val itemCount = recyclerView.adapter?.itemCount ?: 0
            if (nextPosition in 0 until itemCount) {
                val smoothScroller = CustomLinearSmoothScroller(recyclerView.context)
                smoothScroller.targetPosition = nextPosition
                layoutManager.startSmoothScroll(smoothScroller)
                return true
            }
        }
        return false
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.