Decorating RecyclerView (with GridLayoutManager) to display divider between items

后端 未结 9 1450
旧时难觅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:02

    One more simple solution that worked for me. Hope it can be useful.

    class GridItemDecorator(val context: Context, private val spacingDp: Int, private val mGridSize: Int) : RecyclerView.ItemDecoration() {
    
        override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
    
            val resources = context.resources
            val spacingPx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, spacingDp.toFloat(), resources.displayMetrics)
    
            val bit = if (spacingPx > mGridSize) Math.round(spacingPx / mGridSize) else 1
            val itemPosition = (view.layoutParams as RecyclerView.LayoutParams).viewAdapterPosition
    
            outRect.top = if (itemPosition < mGridSize) 0 else  bit * mGridSize
            outRect.bottom = 0
    
            val rowPosition = itemPosition % mGridSize
            outRect.left = rowPosition * bit
            outRect.right = (mGridSize - rowPosition - 1) * bit
    
        }
    }
    

提交回复
热议问题