24

I have my custom view extended from View. There are 3 view constructors:

  1. View(Context context, AttributeSet attrs, int defStyle)
  2. View(Context context, AttributeSet attrs)
  3. View(Context context)

From my activity I call std.setContentView(R.layout.main). The second constructor is getting called in my view. Why the second one? How to know in advance which one will be called and why?

Mark Whitaker
  • 8,465
  • 8
  • 44
  • 68
kompotFX
  • 353
  • 2
  • 4
  • 13

1 Answers1

48

From the Android developer site under documentation for View:

public View (Context context)

Simple constructor to use when creating a view from code.

So this constructor is what you can use to create a View in Java. It will not be called when you inflate from XML.

public View (Context context, AttributeSet attrs)

Constructor that is called when inflating a view from XML. This is called when a view is being constructed from an XML file, supplying attributes that were specified in the XML file. This version uses a default style of 0, so the only attribute values applied are those in the Context's Theme and the given AttributeSet.

The method onFinishInflate() will be called after all children have been added.

So this constructor will be called when you inflate a View from XML when you don't specify a style.

public View (Context context, AttributeSet attrs, int defStyle)

Perform inflation from XML and apply a class-specific base style. This constructor of View allows subclasses to use their own base style when they are inflating. For example, a Button class's constructor would call this version of the super class constructor and supply R.attr.buttonStyle for defStyle; this allows the theme's button style to modify all of the base view attributes (in particular its background) as well as the Button class's attributes.

You should implement all of these constructors, but you can put all of the work in the third one by calling this(context, null) and this(context, attrs, 0) for the first two, respectively.

Community
  • 1
  • 1
skynet
  • 9,898
  • 5
  • 43
  • 52
  • 2
    super(context, attrs) and super(context, attrs, 0) works differentially for me. First one is ok, but second removes original style from a view, so I can't use this(context, attrs, 0). Is it a bug in newer versions of Android? – broot Jan 26 '12 at 14:58
  • 2
    Please don't cascade constructor calls, see my answer below. – Jin Dec 28 '15 at 18:41
  • 1
    I suppose this is Jin's answer: http://stackoverflow.com/a/34301725/326874 – æ-ra-code Aug 12 '16 at 12:06