Skip to content

Instantly share code, notes, and snippets.

@Andrej1A
Last active September 25, 2019 11:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Andrej1A/4e35fea669eb1e728b591173c157b689 to your computer and use it in GitHub Desktop.
Save Andrej1A/4e35fea669eb1e728b591173c157b689 to your computer and use it in GitHub Desktop.
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