Skip to content

Instantly share code, notes, and snippets.

@saeed-younus
Created September 25, 2019 07:48
Show Gist options
  • Save saeed-younus/d5f34cd8ea9305cad1cc29a60ee92a01 to your computer and use it in GitHub Desktop.
Save saeed-younus/d5f34cd8ea9305cad1cc29a60ee92a01 to your computer and use it in GitHub Desktop.
Vertical and Horizontal RecyclerView Divider Item
import android.graphics.Canvas
import android.graphics.drawable.Drawable
import android.util.TypedValue
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
/**
* [RecyclerView] item decoration which adds horizontal divider between items.
*
* @author Muhammad Saeed
*/
@Suppress("unused")
class DividerItemDecoration(
private val drawable: Drawable,
private val marginLeft: Float = 16f,
private val marginRight: Float = 16f,
private val marginTop: Float = 16f,
private val marginBottom: Float = 16f,
private val dividerWidth: Int = 2
) : RecyclerView.ItemDecoration() {
override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
super.onDrawOver(c, parent, state)
for (i in 0 until parent.childCount - 1) {
val child = parent.getChildAt(i)
val params = child.layoutParams as RecyclerView.LayoutParams
if (parent.layoutManager !is LinearLayoutManager) {
return
}
if ((parent.layoutManager as LinearLayoutManager).orientation == RecyclerView.VERTICAL) {
val top = child.bottom - params.bottomMargin - dividerWidth
val bottom = child.bottom - params.bottomMargin
val left = child.left - params.leftMargin + TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
marginLeft,
parent.context?.resources?.displayMetrics
).toInt()
val right = child.right - params.rightMargin - TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
marginRight,
parent.context?.resources?.displayMetrics
).toInt()
drawable.setBounds(left, top, right, bottom)
drawable.draw(c)
} else {
val top = child.top - params.topMargin + TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
marginTop,
parent.context?.resources?.displayMetrics
).toInt()
val bottom = child.bottom - params.bottomMargin - TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
marginBottom,
parent.context?.resources?.displayMetrics
).toInt()
val left = child.right - params.rightMargin - dividerWidth
val right = child.right - params.rightMargin
drawable.setBounds(left, top, right, bottom)
drawable.draw(c)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment