Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need a 4th constructor for Lollipop?

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?

like image 902
Thuy Trinh Avatar asked Dec 28 '14 08:12

Thuy Trinh


1 Answers

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:

  1. Any attribute values in the given AttributeSet.
  2. The style resource specified in the AttributeSet (named "style").
  3. The default style specified by defStyleAttr.
  4. The default style specified by defStyleRes.
  5. 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.
like image 118
gio Avatar answered Oct 21 '22 03:10

gio