Micah Hainline Micah Hainline - 3 months ago 8
Android Question

Do I need all three constructors for an Android custom view?

When creating a custom view, I have noticed that many people seem to do it like this:

public MyView(Context context) {
super(context);
// this constructor used when programmatically creating view
doAdditionalConstructorWork();
}

public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
// this constructor used when creating view through XML
doAdditionalConstructorWork();
}

private void doAdditionalConstructorWork() {

// init variables etc.
}


My first question is, what about the constructor
MyView(Context context, AttributeSet attrs, int defStyle)
? I'm not sure where it is used, but I see it in the super class. Do I need it, and where is it used?

There's another part to this question.

Answer

If you will add your custom View from xml also like :

 <com.mypack.MyView
      ...
      />

you will need the constructor public MyView(Context context, AttributeSet attrs), otherwise you will get an Exception when Android tries to inflate your View.

If you add your View from xml and also spcify the android:style attribute like :

 <com.mypack.MyView
      style="@styles/MyCustomStyle"
      ...
      />

you will also need the third constructor public MyView(Context context, AttributeSet attrs,int defStyle) .

The third constructor is usually used when you extend a style and customize it, and then you would like to set that style to a given View in your layouts.