我正在使用垂直回收器视图并附加了一个 pagerSnapHelper。它工作正常并将项目捕捉到中心位置,但我希望它捕捉到开始(顶部)。我不想使用 linearSnapHelper,因为它不能按我想要的方式工作。GravitySnapHelper 也不会工作,因为它扩展了 linearSnapHelper。如果你可以与扩展的 PagerSnapHelper 共享一个类似的类,那就太好了
问问题
424 次
1 回答
1
所以我通过使用 LinearSnapHelper 实现了一个可行的解决方案。使用库捕捉到顶部
图书馆 - https://github.com/rubensousa/GravitySnapHelper
为了实现类似于寻呼机快照助手的滚动,我使用了下面的代码
// remember to initialize snaphelper
snapHelper = object : GravitySnapHelper(Gravity.TOP){
override fun findTargetSnapPosition(
layoutManager: RecyclerView.LayoutManager,
velocityX: Int,
velocityY: Int
): Int {
val centerView = findSnapView(layoutManager) ?: return RecyclerView.NO_POSITION
val position = layoutManager.getPosition(centerView)
var targetPosition = -1
if (layoutManager.canScrollHorizontally()) {
targetPosition = if (velocityX < 0) {
position - 1
} else {
position + 1
}
}
if (layoutManager.canScrollVertically()) {
// Log.d("debug", "velocityY $velocityY")
targetPosition = if (velocityY < 0) {
position - 1
} else {
position + 1
}
}
val firstItem = 0
val lastItem = layoutManager.itemCount - 1
targetPosition = Math.min(lastItem, Math.max(targetPosition, firstItem))
return targetPosition
}
}
// lower the value higher the speed of scroll
// default is 100f
snapHelper.scrollMsPerInch = 40f
snapHelper.attachToRecyclerView(binding?.yourRecyclerView)
于 2021-01-29T05:37:40.047 回答