I have a RecyclerView
which is attached to a LinearSnapHelper
to snap to center item. When I scroll to the first or last items, these items are not ful
I found a less invasive answer:
private class PagerSelectSnapHelper : LinearSnapHelper() {
override fun findSnapView(layoutManager: RecyclerView.LayoutManager): View? {
// Use existing LinearSnapHelper but override when the itemDecoration calculations are off
val snapView = super.findSnapView(layoutManager)
return if (!snapView.isViewInCenterOfParent(layoutManager.width)) {
val endView = layoutManager.findViewByPosition(layoutManager.itemCount - 1)
val startView = layoutManager.findViewByPosition(0)
when {
endView.isViewInCenterOfParent(layoutManager.width) -> endView
startView.isViewInCenterOfParent(layoutManager.width) -> startView
else -> snapView
}
} else {
snapView
}
}
private fun View?.isViewInCenterOfParent(parentWidth: Int): Boolean {
if (this == null || width == 0) {
return false
}
val parentCenter = parentWidth / 2
return left < parentCenter && parentCenter < right
}
}