I\'m using PagerSnapHelper in RecyclerView. the first item in RecyclerView in left position in the screen. I need the first item in center aligns.
LinearLayoutMa
Here's a simpler version of the accepted answer, that is also more flexible since it doesn't refer to the screen width:
class BoundsOffsetDecoration : ItemDecoration() {
override fun getItemOffsets(outRect: Rect,
view: View,
parent: RecyclerView,
state: RecyclerView.State) {
super.getItemOffsets(outRect, view, parent, state)
val itemPosition = parent.getChildAdapterPosition(view)
// It is crucial to refer to layoutParams.width (view.width is 0 at this time)!
val itemWidth = view.layoutParams.width
val offset = (parent.width - itemWidth) / 2
if (itemPosition == 0) {
outRect.left = offset
} else if (itemPosition == state.itemCount - 1) {
outRect.right = offset
}
}
}
I've written a Medium post describing a step-by-step implementation of this kind of carousels using RecyclerView and SnapHelper, if you need more details.