which constructor to be called for view?

后端 未结 1 1361
广开言路
广开言路 2021-02-01 05:18

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

  1. View(Context context, AttributeSet attrs, int defStyle)
相关标签:
1条回答
  • 2021-02-01 06:08

    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.

    0 讨论(0)
提交回复
热议问题