Android Custom View Constructor

You don’t need the first one, as that just won’t work.

The third one will mean your custom View will be usable from XML layout files. If you don’t care about that, you don’t need it.

The fourth one is just wrong, AFAIK. There is no View constructor that take a Map as the third parameter. There is one that takes an int as the third parameter, used to override the default style for the widget.

I tend to use the this() syntax to combine these:

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

public ColorMixer(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}

public ColorMixer(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    // real work here
}

You can see the rest of this code in this book example.

Leave a Comment