我不会使用
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
}
}
我正在使用这种方法来避免
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
}
}
我在做:
让我知道它是否适合你。
创建自定义 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
}
}