Last active
September 3, 2018 14:59
-
-
Save ericksli/af8bb884b5a94184c516f40cea798692 to your computer and use it in GitHub Desktop.
Draw bottom divider in RecyclerView with customisable show/hide divider and paddings for each item #android
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.Context | |
import android.graphics.Canvas | |
import android.graphics.Paint | |
import android.graphics.RectF | |
import android.support.annotation.ColorRes | |
import android.support.v4.content.res.ResourcesCompat | |
import android.support.v4.view.ViewCompat | |
import android.support.v7.widget.RecyclerView | |
import org.jetbrains.anko.dip | |
class DividerItemDecoration( | |
private val context: Context, | |
private @param:ColorRes val dividerColorResId: Int = R.color.divider, | |
private val shouldDrawDivider: (Int, Int) -> Boolean = { _, _ -> true }, | |
private val dividerPaddingStart: (Int, Int) -> Int = { _, _ -> 0 }, | |
private val dividerPaddingEnd: (Int, Int) -> Int = { _, _ -> 0 } | |
) : RecyclerView.ItemDecoration() { | |
private val dividerPaint = Paint() | |
init { | |
dividerPaint.color = ResourcesCompat.getColor(context.resources, dividerColorResId, null) | |
} | |
override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State?) { | |
super.onDraw(c, parent, state) | |
if (parent.layoutManager == null) return | |
drawDividers(c, parent) | |
} | |
private fun drawDividers(c: Canvas, parent: RecyclerView) { | |
for (i in 0 until parent.childCount) { | |
val child = parent.getChildAt(i) | |
val adapterPosition = parent.getChildAdapterPosition(child) | |
if (adapterPosition == RecyclerView.NO_POSITION) { | |
continue | |
} | |
val childType = parent.adapter.getItemViewType(adapterPosition) | |
if (i != parent.childCount - 1 && shouldDrawDivider(adapterPosition, childType)) { | |
val isRtlLayout = ViewCompat.getLayoutDirection(parent) == ViewCompat.LAYOUT_DIRECTION_RTL | |
val paddingStart = dividerPaddingStart(adapterPosition, childType) | |
val paddingEnd = dividerPaddingEnd(adapterPosition, childType) | |
val paddingLeft = if (isRtlLayout) paddingEnd else paddingStart | |
val paddingRight = if (isRtlLayout) paddingStart else paddingEnd | |
val dividerHeight = context.dip(1) | |
val rect = RectF( | |
child.left.toFloat() + paddingLeft, | |
child.bottom.toFloat() - dividerHeight, | |
child.right.toFloat() - paddingRight, | |
child.bottom.toFloat() | |
) | |
c.drawRect(rect, dividerPaint) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment