Decorating RecyclerView (with GridLayoutManager) to display divider between items

后端 未结 9 1491
旧时难觅i
旧时难觅i 2020-12-07 09:44

What\'s the best and easiest way to decorate RecyclerView to have such look & feel?

\"enter

9条回答
  •  醉话见心
    2020-12-07 09:49

    Below is my custom class that allows equal spacing between grid cells in Kotlin:

    class GridItemOffsetDecoration(private val spanCount: Int, private var mItemOffset: Int) : ItemDecoration() {
    
    override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView,
                                state: RecyclerView.State) {
        val position = parent.getChildAdapterPosition(view)
    
        if (position < spanCount) {
            if (position % 2 == 0) { // left grid
                outRect.set(0, mItemOffset, mItemOffset / 2, mItemOffset / 2)
            } else { // right grid
                outRect.set(mItemOffset / 2, mItemOffset, 0, mItemOffset / 2)
            }
    
        } else if (position % 2 == 0) { // left grid
            outRect.set(0, mItemOffset / 2, mItemOffset, mItemOffset / 2)
    
        } else if (position % 2 == 1) { // right grid
            outRect.set(mItemOffset / 2, mItemOffset / 2, 0, mItemOffset / 2)
    
        } else {
            if (position % 2 == 0) { // left grid
                outRect.set(0, mItemOffset / 2, mItemOffset, mItemOffset)
            } else { // right grid
                outRect.set(mItemOffset / 2, mItemOffset / 2, 0, mItemOffset)
            }
        }
    }
    

    }

    And to add this as a Item Decorator in RecyclerView, add below line:

    /*spanCount is the number of grids, for instance, (2 = 2*2 grid, 3 = 3*3)*/
    binding.rvActiveChallenges.addItemDecoration(GridItemOffsetDecoration(2, resources.getDimensionPixelSize(R.dimen._10dp)))
    

提交回复
热议问题