首页 > 代码库 > 回顾自定义view三个构造函数

回顾自定义view三个构造函数

public class MyCustomView extends View {
    //第一个构造函数
    public MyCustomView(Context context) {
        this(context, null);
    }

    //第二个构造函数
    public MyCustomView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    //第三个构造函数
    public MyCustomView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO:获取自定义属性
    }
    
    ....
}

关于三个构造函数使用时机的说法

  1. 在代码中直接new一个Custom View实例的时候,会调用第一个构造函数.这个没有任何争议.
  2. 在xml布局文件中调用Custom View的时候,会调用第二个构造函数.这个也没有争议.
  3. 在xml布局文件中调用Custom View,并且Custom View标签中还有自定义属性时,这里调用的还是第二个构造函数.

也就是说,系统默认只会调用Custom View的前两个构造函数,至于第三个构造函数的调用,通常是我们自己在构造函数中主动调用的(例如,在第二个构造函数中调用第三个构造函数).

  

回顾自定义view三个构造函数