Search code examples
androidandroid-custom-view

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.


Solution

  • Long story short, No, but if you do override any constructor, then ensure to call super(...) with the exact same number of arguments (like, see Jin's answer for example why).


    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 specify the android:style attribute like :

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

    the 2nd constructor will also be called and default the style to MyCustomStyle before applying explicit XML attributes.

    The third constructor is usually used when you want all of the Views in your application to have the same style.