Hey I want to show divider in top, middle and bottom in Recyclerview.
What I am getting
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
}
}
}