目录
初始Custom View的构造函数
之前写过一篇实现圆形进度条的博客(自定义圆形进度条),通常我们在实现Custom View的时候,都会先继承View并实现View的三个构造函数,例如:
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.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:获取自定义属性
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
}
网上有很多关于三个构造函数使用时机的说法,但是说法正确的却没有几家,这里正式的给大家科普一下:
- 在代码中直接new一个Custom View实例的时候,会调用第一个构造函数.这个没有任何争议.
- 在xml布局文件中调用Custom View的时候,会调用第二个构造函数.这个也没有争议.
- 在xml布局文件中调用Custom View,并且Custom View标签中还有自定义属性时,这里调用的还是第二个构造函数.
也就是说,系统默认只会调用Custom View的前两个构造函数,至于第三个构造函数的调用,通常是我们自己在构造函数中主动调用的(例如,在第二个构造函数中调用第三个构造函数).
至于自定义属性的获取,通常是在构造函数中通过obtainStyledAttributes函数实现的.这里先介绍一下如何生成Custom View的自定义属性.
生成Custom View的自定义属性
Custom View添加自定义属性主要是通过declare-styleable标签为其配置自定义属性,具体做法是: 在res/values/目录下增加一个resources xml文件,示例如下(res/values/attrs_my_custom_view.xml):
<resources>
<declare-styleable name="MyCustomView">
<attr name="custom_attr1" format="string" />
<attr name="custom_attr2" format="string" />
<attr name="custom_attr3" format="string" />
<attr name="custom_attr4" format="string" />
</declare-styleable>
<attr name="custom_attr5" format="string" />
</resources
在上述xml文件中,我们声明了一个自定义属性集MyCustomView,其中包含了custom_attr1,custom_att2,custom_attr3,custom_attr4四个属性.同时,我们还声明了一个独立的属性custom_attr5.
所有resources文件中声明的属性都会在R.attr类中生成对应的成员变量:
public final class R {
public static final class attr {
public static final int custom_attr1=0x7f010038;
public static final int custom_attr2=0x7f010039;
public static final int custom_attr3=0x7f01003a;
public static final int custom_attr4=0x7f01003b;
public static final int custom_attr5=0x7f010000;
}
}
但是声明在标签中的属性,系统还会在R.styleable类中生成相关的成员变量:
public static final class styleable {
public static final int[] MyCustomView = {
0x7f010038, 0x7f010039, 0x7f01003a, 0x7f01003b
};
public static final int MyCustomView_custom_attr1 = 0;
public