Skip to content

Instantly share code, notes, and snippets.

@muhwyndhamhp
Created March 18, 2021 19:36
Show Gist options
  • Save muhwyndhamhp/a157a57d23ed4d78ba704ea13e44793b to your computer and use it in GitHub Desktop.
Save muhwyndhamhp/a157a57d23ed4d78ba704ea13e44793b to your computer and use it in GitHub Desktop.
class PageDotDecorator(
private val itemCount: Int,
private val context: Context?
) : RecyclerView.ItemDecoration() {
companion object {
/**
* Draw Parameters
*/
const val DOT_RADIUS = 3f
const val DOT_PADDING = 6f
}
private var dotStroke: Paint = Paint().apply {
style = Paint.Style.FILL
color = context?.resources?.getColor(R.color.light_grey) ?: Color.GRAY
}
private val dotFill = Paint().apply {
style = Paint.Style.FILL
color = context?.resources?.getColor(R.color.almost_black) ?: Color.GRAY
}
private val dots = mutableListOf<Pair<Float, Float>>()
private val dp = context?.resources?.displayMetrics?.density ?: 0f
private var selectedDot = 0
private var indicatorInitialized = false
override fun onDraw(
canvas: Canvas,
parent: RecyclerView,
state: RecyclerView.State
) {
if (!indicatorInitialized) {
setupIndicators(parent)
}
parent.adapter?.let {
val visibleItem = (parent.layoutManager as? LinearLayoutManager ?: return).findFirstVisibleItemPosition()
if (visibleItem >= 0) selectedDot = visibleItem
for (i in 0 until itemCount) {
drawDot(canvas, dots[i].first, dots[i].second, isSelected = selectedDot == i)
}
}
}
private fun drawDot(canvas: Canvas, x: Float, y: Float, isSelected: Boolean = false) {
canvas.drawCircle(x, y, DOT_RADIUS * dp, if (isSelected) dotFill else dotStroke)
}
private fun setupIndicators(recyclerView: RecyclerView) {
indicatorInitialized = true
val indicatorTotalWidth = 2 * DOT_RADIUS + DOT_PADDING
val indicatorPosX = ((recyclerView.width - (indicatorTotalWidth * itemCount * dp)) / 2f) + (DOT_PADDING * dp)
val indicatorPosY = recyclerView.height - (DOT_RADIUS * 5 * dp)
for (i in 0 until itemCount) dots.add((indicatorPosX + i * indicatorTotalWidth * dp) to indicatorPosY)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment