4个构造方法
例:自定义一个类
public class TestView extends View {
//第一个构造方法
//在java代码里声明一个View时候所用(new的时候会用到)
public TestView(Context context) {
super(context);
}
//第二个构造方法
//在xml布局文件中使用时自动调用
public TestView(Context context, AttributeSet attrs) {
super(context, attrs);
}
//第三个构造方法
//不会自动调用,如果有默认style时,在第二个构造函数中调用
public TestView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
//第四个构造方法
//不会自动调用,API >21时才能使用,如果有默认style时在第二个构造函数中调用
public TestView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
一般使用前三个构造方法就可以了
构造方法中的参数
参数 | 说明 |
---|---|
context | 上下文 |
attrs | 我们在XML中配置的属性集合 |
defStyleAttr | 当前主题中的一个属性,为视图提供默认值的样式资源. 只要在主题中对这个属性赋值,该View就会自动应用这个属性的值 |
defStyleRes | 提供视图默认值的样式资源的资源标识符,只有在第三个参数defStyleAttr为0,或者主题中没有找到这个defStyleAttr属性的赋值时,才可以启用!而且这个参数不再是属性了,而是真正的style。其实这也是一种低级别的“默认主题”,即在主题未声明属性值时,我们可以主动的给一个style,使用这个构造函数定义出的View,其主题就是这个定义的defStyleRes |
属性可以在多个地方进行赋值,优先级为:XML直接定义 > XML中style引用 > defStyleAttr > defStyleRes > theme直接定义
实际使用中的写法
例:
public class TestView extends View {
//第一个构造方法调用第二个构造方法
public TestView(Context context) {
this(context, null);
}
//第二个构造方法调用第三个构造方法
public TestView(Context context, AttributeSet attrs) {
thi(context, attrs, 0);
}
//第三个构造方法调用第四个构造方法
public TestView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr, 0);
//如果只使用三个构造方法,无论使用前面的哪种构造方法,最终都会调用此构造方法;在此构造方法中进行初始化操作
}
//第四个构造方法
public TestView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
//如果使用了四个构造方法,无论使用前面的哪种构造方法,最终都会调用此构造方法;在此构造方法中进行初始化操作
}
}