Decorating RecyclerView (with GridLayoutManager) to display divider between items

后端 未结 9 1449
旧时难觅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 10:07

    Here's my implementation in Kotlin. I modified code from other answers so that divider is shown also for full spanned items.

    import android.graphics.Rect
    import android.view.View
    import androidx.recyclerview.widget.GridLayoutManager
    import androidx.recyclerview.widget.RecyclerView
    
    class GridDividerItemDecoration(private val spacing: Int) : RecyclerView.ItemDecoration() {
    
        override fun getItemOffsets(
            outRect: Rect,
            view: View,
            parent: RecyclerView,
            state: RecyclerView.State
        ) {
            val position = parent.getChildAdapterPosition(view)
    
            val totalSpanCount = getTotalSpanCount(parent)
            val spanSize = getItemSpanSize(parent, position)
    
            outRect.top = if (isInTheFirstRow(position, totalSpanCount)) 0 else spacing
            outRect.left = if (isFirstInRow(position, totalSpanCount, spanSize)) 0 else spacing / 2
            outRect.right = if (isLastInRow(position, totalSpanCount, spanSize)) 0 else spacing / 2
            outRect.bottom = 0
        }
    
        private fun isInTheFirstRow(position: Int, totalSpanCount: Int): Boolean =
            position < totalSpanCount
    
        private fun isFirstInRow(position: Int, totalSpanCount: Int, spanSize: Int): Boolean =
            if (totalSpanCount != spanSize) {
                position % totalSpanCount == 0
            } else true
    
        private fun isLastInRow(position: Int, totalSpanCount: Int, spanSize: Int): Boolean =
            isFirstInRow(position + 1, totalSpanCount, spanSize)
    
        private fun getTotalSpanCount(parent: RecyclerView): Int =
            (parent.layoutManager as? GridLayoutManager)?.spanCount ?: 1
    
        private fun getItemSpanSize(parent: RecyclerView, position: Int): Int =
            (parent.layoutManager as? GridLayoutManager)?.spanSizeLookup?.getSpanSize(position) ?: 1
    }
    

    Result:

提交回复
热议问题