Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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)
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement