在XML布局文件中使用Android系统提供的View组件时,开发者可以指定多个属性,这些属性可以控制View组件的外观。我们也可以开发自己的View组件,同时也可以给自定义组件指定自定义属性,这就是所谓的属性资源,一般属性资源放在attrs.xml或者以attrs为开头的xml文件中。
属性资源资源文件存放在res/values目录下,属性资源文件的根元素是<resources.../>,该元素里面包含两个子元素:
- attr:定义一个属性
- declare-styleable:定义一个styleable对象,每个styleable对象就是一组attr属性的集合。
下面我们介绍如何自定义属性资源,并在自定义组件中使用自定义资源
1.首先在attrs.xml中定义属性资源
<declare-styleable name="testView">
<attr name="duration" format="integer"></attr>
</declare-styleable>
</resources>
name=“testView"有什么作用呢,其实只有一个作用,在生成的R.java中有一个数组名:testView,如下:
public static final class styleable {
public static final int[] testView = {
0x7f010000
};
attr子元素的作用,在R.java的attr数组中生成一个项,如下:
public final class R {
public static final class attr {
public static final int duration=0x7f010000;
}
2.
在自定义View类里引用attrs文件里定义的属性为自己的属性设置值
public dbView(Context context,AttributeSet attrs) {
super(context, attrs);
TypedArray typeArray=context.obtainStyledAttributes(attrs, R.styleable.testView);
int duration=typeArray.getInt(R.styleable.testView_duration, 0);
alphaDelta=255*SPEED/duration;
}
3.使用自定义组件,并设置属性
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:debai="http://schemas.android.com/apk/res/com.example.attrtest"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
tools:context=".MainActivity" />
<com.example.attrtest.dbView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/ee"
debai:duration="60000"
/>
</LinearLayout>
注意:属性一旦定义完毕,任何组件都可以使用