Sobes.tech
Middle

How many constructors should a custom View in Android have?

sobes.tech AI

Answer from AI

Three:

  1. View(Context context): Used when creating a View programmatically.
  2. View(Context context, @Nullable AttributeSet attrs): Used when creating a View from XML. AttributeSet contains attributes specified in XML.
  3. View(Context context, @Nullable AttributeSet attrs, int defStyleAttr): Used when creating a View from XML with a default style specified. defStyleAttr indicates the attribute in the current theme from which to obtain the style.

Typically, in a custom view, two or three of these constructors are overridden, calling the corresponding superclass constructor and performing initialization.

public class MyCustomView extends View {

    public MyCustomView(Context context) {
        super(context);
        init(null, 0); // Call general initialization
    }

    public MyCustomView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(attrs, 0); // Call general initialization
    }

    public MyCustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs, defStyleAttr); // Call general initialization
    }

    // General initialization method
    private void init(@Nullable AttributeSet attrs, int defStyleAttr) {
        // Read attributes from attrs considering defStyleAttr
        // Initialize fields, configure View
    }
}
How many constructors should a custom View in Android… - sobes.tech