first item center aligns in SnapHelper in RecyclerView

前端 未结 2 515
粉色の甜心
粉色の甜心 2021-02-08 14:33

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         


        
2条回答
  •  再見小時候
    2021-02-08 14:58

    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.

提交回复
热议问题