在通过xml文件构造view组件的时候,往往都要使用到AttributeSet和defStyle这个两个参数,例如Button组件的构造方法Button(Context ctx, AttributeSet attrs, int defStyle)中,ctx会调用obtainStyledAttributes( AttributeSet set, int[] attrs, int defStyleAttr, int defStyleRes)方法获得一个TypedArray,然后根据这个TypeArray来设置组件的属性。obtainStyledAttributes这类方法有好几个,真正的实现是Resources.Theme类,分别是:
(2) obtainStyledAttributes( int resid, int[] attrs) : TypeArray
(3) obtainStyledAttributes(int[] attrs) : TypeArray
在方法(1)里根据attrs确定要获取哪些属性,然后依次通过其余3个参数来取得相应的属性值,属性值获取的优先级从高到低依次是set, defStyleAttr, defStyleRes. defStyleAttr是一个reference, 它指向当前Theme中的一个style, style其实就是各种属性的集合,如果defStyleAttr为0或者在Theme中没有找到相应的style, 则 才会尝试从defStyleRes获取属性值,defStyleRes表示的是一个style的id, 当它为0时也无效。方法(2)和(3)分别表示从style或Theme里获取属性值。
<declare-styleable name="LabelView">
<attr name="text" format="string" />
<attr name="textColor" format="color" />
<attr name="textSize" format="dimension" />
</declare-styleable>
<attr name="layout_height" format="dimension">
<enum name="fill_parent" value="-1" />
<enum name="match_parent" value="-1" />
<enum name="wrap_content" value="-2" />
</attr>
<declare-styleable name="Gallery1">
<attr name="android:galleryItemBackground" />
</declare-styleable>
在layout布局中使用自定义的属性,要指明包名称,需要先定义,例如xmlns:app="http://schemas.android.com/apk/res/your_package_name", 然后就可以这样app:text, app:textSize来设置属性了。
int getAttributeNameResource(int index);
int getAttributeResourceValue(int index, int defaultValue);
前一个方法获取的就是attr属性名称的id,也也就是attr类定义的数值,后一个方法获取的才是attr属性值。