Home > Back-end >  Add Divider Top,Middle and Bottom of Recyclerview Kotlin
Add Divider Top,Middle and Bottom of Recyclerview Kotlin

Time:10-02

Hey I want to show divider in top, middle and bottom in Recyclerview. enter image description here

What I am getting

enter image description here

CodePudding user response:

You don't need to write your own class. The way you're doing it does not account for the thickness of the divider, so it could lead to inaccurate padding in your list items. Use the provided class DividerItemDecoration.

However, it is also missing a divider above the top item. Here's a class you can add as a second decoration. It draws a divider over only the first item, so you can customize it to look different from the rest, which I think is a good idea for usability reasons. I based it off the source of DividerItemDecoration so it properly accounts for padding and clipping.

class TopDividerItemDecoration(val context: Context) : RecyclerView.ItemDecoration() {
    private val bounds = Rect()
    private var _drawable: Drawable? =
        context.obtainStyledAttributes(intArrayOf(android.R.attr.listDivider)).use {
            it.getDrawable(0)
        }
    var drawable: Drawable
        get() = _drawable
            ?: error("A drawable must be set before use. Current theme lacks default divider.")
        set(value) {
            _drawable = value
        }

    override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        if (parent.layoutManager == null || parent.childCount == 0)
            return

        c.save()
        if (parent.clipToPadding) {
            c.clipRect(
                parent.paddingLeft, parent.paddingTop, parent.width - parent.paddingRight,
                parent.height - parent.paddingBottom
            )
        }

        val child = parent.getChildAt(0)
        parent.getDecoratedBoundsWithMargins(child, bounds)
        val top = bounds.top   child.translationY.roundToInt()
        val bottom = top   drawable.intrinsicHeight
        drawable.setBounds(0, top, parent.width, bottom)
        drawable.draw(c)

        c.restore()
    }

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        super.getItemOffsets(outRect, view, parent, state)
        if (parent.getChildLayoutPosition(view) == 0) {
            outRect.top  = drawable.intrinsicHeight
        }
    }
}
  • Related