Android 自定义View(控件) 中的构造方法详解

Android 自定义View的构造方法详解

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);
        //如果使用了四个构造方法,无论使用前面的哪种构造方法,最终都会调用此构造方法;在此构造方法中进行初始化操作
    }
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值