Skip to content

Instantly share code, notes, and snippets.

@renaudmathieu
Last active November 17, 2018 16:07
Show Gist options
  • Save renaudmathieu/305cb9ef7cef0c1d28a392319dffc7d1 to your computer and use it in GitHub Desktop.
Save renaudmathieu/305cb9ef7cef0c1d28a392319dffc7d1 to your computer and use it in GitHub Desktop.
Divider Item decoration for RecyclerView in Kotlin with paddings
import android.content.Context
import android.graphics.Canvas
import android.graphics.drawable.Drawable
import android.support.v4.content.ContextCompat
import android.support.v7.widget.RecyclerView
class ListPaddingDecoration(
context: Context,
val paddingLeft: Int,
val paddingRight: Int
) : RecyclerView.ItemDecoration() {
private var mDivider: Drawable? = null
init {
mDivider = ContextCompat.getDrawable(context, R.drawable.divider_medium)
}
override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State?) {
val left = parent.paddingLeft + paddingLeft
val right = parent.width - parent.paddingRight + paddingRight
val childCount = parent.childCount
for (i in 0 until childCount) {
val child = parent.getChildAt(i)
val params = child.layoutParams as RecyclerView.LayoutParams
val top = child.bottom + params.bottomMargin
val bottom = top + (mDivider?.intrinsicHeight ?: 0)
mDivider?.let {
it.setBounds(left, top, right, bottom)
it.draw(c)
}
}
}
}
@renaudmathieu
Copy link
Author

You just need to specify a color in R.drawable.divider_medium

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@android:color/black" />
    <size
        android:height="1dp"
        android:width="1dp" />

</shape>

and add it to your recyclerView

recyclerView.addItemDecoration(
    ListPaddingDecoration(
        activity as Activity,
        resources.getDimension(80),
        0
    )
)

Optim: set a custom drawable and orientation.

@loicteillard
Copy link

A little mistake it's val right = parent.width - parent.paddingRight - paddingRight

But thank you it helps me !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment