Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Template for an Android custom view. The example shows a vertical dotted line.
/**
* VerticalDottedLineView
* Add to attrs.xml:
* <declare-styleable name="VerticalDottedLineView">
* <attr name="dots_color" format="color" />
* </declare-styleable>
*/
class VerticalDottedLineView : View {
private var dotColor: Int = 0
private var dotDiameterPx: Float = 0.0f
private var dotMarginPx: Float = 0.0f
private var numberOfDots: Int = 0
private lateinit var dotPaint: Paint
constructor(context: Context) : super(context) {
init(context, null)
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
init(context, attrs)
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
init(context, attrs)
}
private fun init(context: Context, attrs: AttributeSet?) {
val attributes = context.obtainStyledAttributes(attrs, R.styleable.VerticalDottedLineView)
dotColor = attributes.getColor(
R.styleable.VerticalDottedLineView_dots_color,
ContextCompat.getColor(context, R.color.black)
)
attributes.recycle()
dotDiameterPx = DOT_DIAMETER_DP.dpToPx()
dotMarginPx = DOT_MARGIN_DP.dpToPx()
dotPaint = Paint().apply {
color = dotColor
style = Paint.Style.FILL
isAntiAlias = true
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
numberOfDots = ((h - (dotMarginPx * 2.0f)) / (dotDiameterPx + dotMarginPx)).toInt()
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
for (i in 0 until numberOfDots) {
val dotX = width / 2.0f
val dotY = (height / numberOfDots) * i + dotMarginPx
canvas.drawCircle(dotX, dotY, dotDiameterPx / 2.0f, dotPaint)
}
}
private fun Float.dpToPx(): Float =
TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this, resources.displayMetrics)
companion object {
private var DOT_DIAMETER_DP = 3.0f
private var DOT_MARGIN_DP = 6.0f
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment