I started a project targeting Android Lollipop (21), and created a custom view. When I generated constructors for the view, I got a new 4th constructor which takes more params than the others.
public class FooView extends FrameLayout {
public FooView(Context context) {
super(context);
}
public FooView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FooView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
// This 4th constructor
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public FooView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
}
My question is, why do we need it? What would happen if I remove this constructor and run the app on Lollipop?
Information from official doc
public View (Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
Added in API level 21
Perform inflation from XML and apply a class-specific base style from a theme attribute or style resource. This constructor of View allows subclasses to use their own base style when they are inflating.
When determining the final value of a particular attribute, there are four inputs that come into play:
- Any attribute values in the given AttributeSet.
- The style resource specified in the AttributeSet (named "style").
- The default style specified by defStyleAttr.
- The default style specified by defStyleRes.
- The base values in this theme.
Each of these inputs is considered in-order, with the first listed taking precedence over the following ones. In other words, if in the AttributeSet you have supplied , then the button's text will always be black, regardless of what is specified in any of the styles.
Parameters
- context The Context the view is running in, through which it can access the current theme, resources, etc.
- attrs The attributes of the XML tag that is inflating the view.
- defStyleAttr An attribute in the current theme that contains a reference to a style resource that supplies default values for the view. Can be 0 to not look for defaults.
- defStyleRes A resource identifier of a style resource that supplies default values for the view, used only if defStyleAttr is 0 or can not be found in the theme. Can be 0 to not look for defaults.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With