Android Custom Views: Basics

A simple custom view

In this series of posts I will be developing a custom View and I will be taking you through all the steps necessary to develop your own custom views and making them look beautiful. For the app that I am currently developing, I will be needing a colour picker. I know there a tons of colour pickers out there but I want to create a colour picker with my own design. Like all my tutorial code so far, this piece will be distrbuted under the MIT license.

The first thing to do if you want to create your own View is to create a class that extends View.


public class ColorPicker extends View {

  public ColorPicker(Context context) {
  public ColorPicker(Context context, AttributeSet attrs) {
    super(context, attrs);
  public ColorPicker(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);

The View class has three constructors, each taking a different number of arguments. To keep our ColorPicker class flexible and to conform to the general standard we should also implement these three constructors. The first constructor is usually used when programmatically creating the View in your own code. The Context is the context in which the View is created. The context allows access to the resources, the current theme and other things. The context is essential and a View cannot exist without it. The second constructor is called when the View is inflated from an XML layout resource. The AttributeSet is a set of attributes that have been defined in the XML. It is possible to add and parse custom attributes to your view but for now we will just pass the attributes to the superclass. The third constructor should only be called from child classes of our ColorPicker class. This parameter
provides a way of providing different default styling to views of different types. We will come back to this in a later post.

Including the View in XML

We have now created a custom ColorPicker view. There is currently nothing distinguishing it from a simple View class because it doesn’t contain any new code. But before we create content for our view we want to be able to test it in XML layouts. The question arises, what we have to do to make the view accessible from XML layouts. Luckily the answer is, nothing! We can immediately use the view in our XML but we have to provide the full package name. Here is an example of an XML layout using the ColorPicker view.

<RelativeLayout xmlns:android=""
    tools:context="" >


A simple custom view

A simple custom view

We can set the same attributes that we can set on any other view. By setting the background colour to blue and by specifying the width and height to 200dp we have created a blue square. A screenshot of the resulting layout can be seen on the right. In the next post we will learn how to draw something into the view by overriding the onDraw method.