Middle
How many constructors should a custom View in Android have?
sobes.tech AI
Answer from AI
Three:
View(Context context): Used when creating a View programmatically.View(Context context, @Nullable AttributeSet attrs): Used when creating a View from XML.AttributeSetcontains attributes specified in XML.View(Context context, @Nullable AttributeSet attrs, int defStyleAttr): Used when creating a View from XML with a default style specified.defStyleAttrindicates 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
}
}