Codementor Events

Handy Code Template for Android custom views

Published Aug 01, 2020

Creating custom view on Android in Java required extending a View class and providing these 3 overloaded constructors (or at least one with only the Context if you planned to use the custom view only in a programmatic way):

public class CustomView extends View {

    public CustomView(Context context) {
        this(context, null);
    }

    public CustomView(Context context, 
                      @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomView(Context context, 
                      @Nullable AttributeSet attrs, 
                      int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
}

Well, that was a little bit verbose but one could get used to it.

Since Kotlin came in however, developers can use its expressiveness to drastically reduce the boilerplate code.
The equivalent of the above in Kotlin is this:

class CustomView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr)

The magical piece here is the @JvmOverloads annotation which instructs the compiler to create all the variations of the class constructor based on the fact that some of the parameters are optional.

Screenshot 2020-08-01 at 18.10.06.png

If you like this approach to making you more productive, you will appraciate the fact that you can go even further and create a Code Template for yourself that automatically generates the code for you: Here is how it's done from the Preferences window:
Screenshot 2020-08-01 at 18.32.09.png

Once you have this in place, you will use this context menu to create your new custom view from the template you have just created, give your class a name and you are good to go:
Screenshot 2020-08-01 at 18.37.37.png

Hope you find this tip useful. Happy coding!

Discover and read more posts from Adrian Lesniak
get started
post commentsBe the first to share your opinion
Show more replies