首页 > 解决方案 > RecyclerView show many items and make current item in center

问题描述

Like this.

|-----------------------------------|
|                                   |
|                                   |
|         |---------------|    |----|
|         |               |    |    |
|         |               |    |    |
|         |               |    |    |
|         |               |    |    |
|         |       1       |    |  2 |
|         |               |    |    |
|         |               |    |    |
|         |               |    |    |
|         |               |    |    |
|         |---------------|    |----|
|                                   |
|                                   |
|-----------------------------------|


|-----------------------------------|
|                                   |
|                                   |
|----|    |---------------|    |----|
|    |    |               |    |    |
|    |    |               |    |    |
|    |    |               |    |    |
|    |    |               |    |    |
|  1 |    |       2       |    |  3 |
|    |    |               |    |    |
|    |    |               |    |    |
|    |    |               |    |    |
|    |    |               |    |    |
|----|    |---------------|    |----|
|                                   |
|                                   |
|-----------------------------------|

I have try SnapHelper, but I don't known how

标签: android-recyclerview

解决方案


为了使第一个和最后一个项目居中,您需要在 RecyclerView 的开头和结尾创建额外的空间。一个简单的方法是使用 ItemDecoration,如下所示:

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
        }
    }
}

对于“中心”效果,您应该使用PagerSnapHelper

PagerSnapHelper().attachToRecyclerView(recyclerView)

如果您需要更多详细信息,我已经写了一篇Medium 文章,描述了使用 RecyclerView 和 SnapHelper 逐步实现这种轮播。


推荐阅读