Created
December 9, 2019 08:18
-
-
Save mvasilova/ae3830e57a3779716d26fca1145fa386 to your computer and use it in GitHub Desktop.
Divider for item's RecyclerView
This file contains 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.graphics.Canvas | |
import android.graphics.Paint | |
import android.graphics.Rect | |
import android.view.View | |
import androidx.core.graphics.withTranslation | |
import androidx.core.view.children | |
import androidx.recyclerview.widget.RecyclerView | |
class DividerItemDecoration( | |
private val strokeColor: Int, | |
private val strokeWidth: Int, | |
private val marginStart: Float = 0.0F, | |
private val marginEnd: Float = marginStart, | |
private val horizontalSpacing: Int = 0, | |
private val verticalSpacing: Int = horizontalSpacing | |
) : RecyclerView.ItemDecoration() { | |
private val dividerPaint = Paint().apply { | |
color = strokeColor | |
strokeWidth = [email protected]() | |
flags = Paint.ANTI_ALIAS_FLAG | |
} | |
override fun getItemOffsets( | |
outRect: Rect, | |
view: View, | |
parent: RecyclerView, | |
state: RecyclerView.State | |
) { | |
outRect.set(horizontalSpacing, verticalSpacing, horizontalSpacing, verticalSpacing) | |
} | |
override fun onDrawOver(canvas: Canvas, parent: RecyclerView, state: RecyclerView.State) { | |
parent.children.forEach { child -> | |
canvas.withTranslation( | |
x = 0.0F, | |
y = verticalSpacing.toFloat() | |
) { | |
val lineTopY = child.top - strokeWidth/ 2f | |
drawLine( | |
child.left + marginStart, | |
lineTopY, | |
child.right - marginEnd, | |
lineTopY, | |
dividerPaint | |
) | |
if (child.isLastItem(parent, state.itemCount)) { | |
val lineBottomY = child.bottom - strokeWidth/ 2f | |
drawLine( | |
child.left + marginStart, | |
lineBottomY, | |
child.right - marginEnd, | |
lineBottomY, | |
dividerPaint | |
) | |
} | |
} | |
} | |
} | |
private fun View.isLastItem(parent: RecyclerView, itemCount: Int) = | |
parent.getChildAdapterPosition(this) == itemCount - 1 | |
} | |
//Usages | |
val divider = DividerItemDecoration( | |
ContextCompat.getColor(context!!, R.color.colorGray), | |
2.dpToPx, | |
marginStart = 0f, | |
marginEnd = 0f | |
) | |
recyclerView.addItemDecoration(divider) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment