美文网首页
自定义view构造函数

自定义view构造函数

作者: couriravant | 来源:发表于2020-02-29 19:18 被阅读0次
public MView(Context context) {
    super(context);
}
 
public MView(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
}
 
public MView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

三个方法的区别主要
a: 代码中直接实例化自定义控件,会调用第一个构造函数
b: xml布局使用自定义控件,会调用第二个构造函数
c: xml布局使用自定义控件,并且控件含有自定义属性,仍然调用的是第二个构造函数.
d: defStyleAttr:这个参数是指,在当前view所属Activity的Theme(或如果这个Activity没有设置Theme,那么就是指Application的Theme)对控件设置的属性
e: defStyleRes:这个参数在构造方法中接收的一样是一个int类型的style,我们依然可以按照R.style.xxx的方式设置给它
通过theme设置属性的方法可见:
https://blog.csdn.net/nannan1989yue/article/details/80610013?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task

自定义属性,res/values/目录下新建attrs.xml,比如

<resources>
    <declare-styleable name="maicai_home_CircularCoverView">
        <attr name="maicai_home_left_top_radius" format="dimension" />
        <attr name="maicai_home_cover_color" format="color" />
    </declare-styleable>
</resources>

format属性有11种,比如:color表示颜色,reference表示引用资源id,dimension表示尺寸,
refer:https://www.jianshu.com/p/8844de6addb3
使用时,调用如下:

 TypedArray typedArray =
                    context.obtainStyledAttributes(attrs, R.styleable.maicai_home_CircularCoverView);
            if (typedArray != null){
                leftTopRadians = typedArray
                        .getDimensionPixelSize(R.styleable.maicai_home_CircularCoverView_maicai_home_left_top_radius, radius);
                leftBottomRadians = typedArray
                  。。。
                coverColor = typedArray.getColor(R.styleable.maicai_home_CircularCoverView_maicai_home_cover_color, coverColor);
                typedArray.recycle();
            }

一般情况下用前两个即可,如果需要用到主题参数,可以考虑3、4构造函数。


    public TestView(Context context) {
        this(context, null);
    }

    public TestView(Context context,   @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TestView(Context context,   @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    @TargetApi(21)
    public TestView(Context context,  AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context, attrs);
    }

相关文章

网友评论

      本文标题:自定义view构造函数

      本文链接:https://www.haomeiwen.com/subject/smdmhhtx.html