Android Custom Views with Kotlin

Ashish Kumar
3 min readMay 11, 2020

--

This is Part I of Learning Android Series (a.k.a project “The Circle”)

  1. Part I (You are here)
  2. Part II
  3. Part III
  4. Coming Soon…

This tutorial will walk you through the process of creating custom views detecting click on them and changing it dynamically, we will create a circle which will change its colour if clicked, all by using custom views.

Extending View

The first step in creating custom view is to extend View this allows us to draw on Canvas, Create a class that extends a View and we have to implement multiple constructors.

With the help of Kotlin we can simplify the multiple constructor boilerplate by using @JvmOverloads annotations before constructor. It will automatically generated constructor code .

Drawing Circle

Awesome now we can finally start drawing on Canvas, lets start by making a simple circle, just do

val paint = Paint().apply {
color = Color.RED
}
private val centre = PointF(50, 50)override fun onDraw(canvas: Canvas?) {
canvas?.drawCircle(centre.x, centre.y, 50, paint)
}

The drawCircle method takes 4 arguments, centre x, centre y, radius and paint.

Create an XML file add your custom view to it

<com.example.thecircle.customview.CircleView
android:id="@+id/circle_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

Awesome 😎 , Now you can see a red circle on your screen.

Before moving forward let’s fix one thing, our CircleView takes the whole screen height and width even if we did warp_content .This is because the height and width of our view is not being calculated yet.

override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
setMeasuredDimension(circleDiameter, circleDiameter);
}

Now we can centre the view in our XML layout easily

Detecting Click

Now let’s do the final task, detect click inside the circle ⭕️ and change colour of the circle.

We calculate the distance between touchPoint and centre of the circle and if its smaller than or equal to circle radium we clicked inside it else we clicked outside it.

We call callOnClick() method to trigger onClickListener on our view.

Changing colour

Lets add few methods which will help in changing colour, we will set random colour everytime it is clicked

fun setRandomColor() {
paint.color =
getRandomColor()
}

private fun getRandomColor(): Int {
return Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256))
}

Now from out layout XML

circle_view.setOnClickListener {
(it as CircleView).setRandomColor()
it.invalidate()
}

The invalidate() triggers the onDraw() which will re-draw our circle with new random colour.

Congratulations 🥳 you now know how to create custom views and how to detect click on them and also how to change its colour.

Keep Learning, Stay Cool 😎 .

--

--

Ashish Kumar

Computer Science student | Android Developer | Full Stack Developer