Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 677
Micah Hainline Avatar asked Oct 07 '22 08:10

Micah Hainline


People also ask

What is custom view in android?

Custom Views is just a way to make an android developer a painter. When you need to create some custom and reuse the views when it is not provided by the Android Ecosystem. Custom Views can be used as widgets like TextView, EditText etc.

Why do we require custom view?

To summarize, the use of a Layout as the basis for a Custom Control has a number of advantages, including: You can specify the layout using the declarative XML files just like with an activity screen, or you can create views programmatically and nest them into the layout from your code.


1 Answers

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.

like image 141
Ovidiu Latcu Avatar answered Oct 14 '22 13:10

Ovidiu Latcu