I had a RecyclerView configured with various Extension Functions to center and see the next item:
fun RecyclerView.pageSnap() = this.post {
if (this.onFlingListener == null) PagerSnapHelper().attachToRecyclerView(this)
}
fun RecyclerView.snapCenterWithMargin(left: Int, top: Int, right: Int, bottom: Int) {
val offsetItemDecoration = SnapCenterWithMargin(left, top, right, bottom)
this.addItemDecoration(offsetItemDecoration)
}
private class SnapCenterWithMargin(
private val left: Int,
private val top: Int,
private val right: Int,
private val bottom: Int
) : RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
view.measure(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
val position = parent.getChildAdapterPosition(view)
val firstItem = 0
val lastItem = state.itemCount - 1
when (position) {
firstItem -> {
val firstPadding = (parent.width) / 2 - view.measuredWidth / 2
outRect.set(firstPadding, 0, 0, 0)
}
lastItem -> {
val lastPadding = (parent.width) / 2 - view.measuredWidth / 2
outRect.set(0, 0, lastPadding, 0)
}
else -> {
outRect.set(left, top, right, bottom)
}
}
}
}
The problem is the ListAdapter animations are bad with this approach. Then I tried to move to ViewPager2 but I can't get this behavior (see the next screen and keep items centered).