在android开发中,我们经常会涉及到自定义View,View有3个构造方法(可能以后会更多),如下:
public CircleView(Context context) {
this(context,null);
}
public CircleView(Context context, AttributeSet attrs) {
this(context,attrs,R.attr.customViewStyle);
}
public CircleView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
//初始化属性
TypedArray array=context.obtainStyledAttributes(attrs, R.styleable.customView,defStyleAttr,0);
circleWidth=array.getDimensionPixelSize(R.styleable.circleView_circleWidth,DEFALUT_CIRCLE_WIDTH);
array.recycle();
init();
}
第一个构造方法是提供给我们在代码中生成控件使用的,第二个方法是在XML布局文件中插入控件使用的,其中attrs参数就是我们在XML中定义控件的属性(包含自定义的属性),其实第二个构造函数也是调用第三个构造函数,这里我在第三个参数传入R.attr.customViewStyle,第三个方法的第三个参数defStyleAttr的意义是从APP或者Activity的Theme中设置的该控件的属性的默认值,如下:
这是我再attrs文件中定义的属性,也就是上面构造方法中传入的参数
<attr name="customViewStyle" format="reference" />
然后我们需要在App 或者Activity的Theme中设置它的值
<style name="AppTheme" parent="AppBaseTheme">
<!-- All customizations that are NOT specific to a particular API-level can go here. -->
<item name="customViewStyle">@style/custom_view_style</item>
</style>
其中的custom_view_style
<style name="custom_view_style">
<item name="circleWidth">8dp</item>
</style>
这样当你的XML文件中没有给该控件的circleWidth定义值的时候,默认值就是8dp。
注意:
TypedArray array=context.obtainStyledAttributes(set, attrs, defStyleAttr, defStyleRes);
该方法的第四个参数defStyleRes,可以直接传入自定义的style,如果defStyleAttr为0,defStyleRes才会起作用。
android控件获取属性值的优先顺序:
1.在XMl文件中直接定义;
2.在XMl文件引用的style;
3.就是从如上所说的defStyleAttr中取值;
4.从defStyleRes取值;
5.从Activity或者Application的Theme中取值;