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

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.

Leave a Comment