View Constructors in Kotlin

David Perez
Livefront
Published in
2 min readDec 7, 2020
Photo by SevenStorm

An extremely common thing to do when working on an Android app is to create reusable views. Historically this involves creating anywhere from 2 to 4 different constructors that initialize things like custom view properties. This was mandatory because Java forced you to specify each constructor manually and while you can still do it this way, there is now a much simpler way using the @JvmOverloads annotation when defining the constructor in Kotlin. The annotation is documented as such.

Instructs the Kotlin compiler to generate overloads for this function that substitute default parameter values.

In other words, all the methods (constructors in this case) will be written for you using the default values in places that do not provide their own.

A basic view constructor.

The example above will cover most custom views: just add some generic default values for the optional parameters and you're done. There are instances where you can have issues with those generic values, though. Extending an EditText is one such instance where a specific style is needed in order to make sure it looks correct.

A view constructor with a specialized style.

You can see the second example is extremely close to the first with only 2 primary differences:

  • The constructor only takes three parameters; this is because the EditText does not have the fourth constructor available.
  • The default value for defStyleAttr is not 0. This is because the view internally has a style set and using 0 would replace it, causing the view to look incorrect. The value I have used is the same one the view would apply internally maintaining a consistent baseline for the view before applying all the customizations.

Knowing when to use a specialized style can be difficult, but you will usually know when you first see the view. You can also investigate the source code for the View you are extending to see what it is doing.

David builds custom views at Livefront.

--

--