一些项目需求,需要自定义属性,也就是在values 的文件夹下面新建 attrs.xml 文件。会配置一些属性。使用属性时就遇到了 TypedArray 类的使用。以前没有使用过,也就没深入研究,今天遇到了,就百度了一下。也算有所了解。首先创建 attrs.xml文件。
1
2
3
4
5
6
7
8
9
10
11
|
<?xml version=
"1.0"
encoding=
"utf-8"
?>
<resources>
<declare-styleable name=
"RainView"
>
<attr name=
"rainNum"
format=
"integer"
/>
<attr name=
"size"
format=
"integer"
/>
<attr name=
"rainColor"
format=
"integer"
/>
<attr name=
"randColor"
format=
"boolean"
/>
</declare-styleable>
</resources>
|
可以看到,定义了四个属性。首先在布局文件中,这里说的是自定义组件的时候,在布局文件的顶部加上这一句话:
1
2
3
4
5
6
|
<RelativeLayout xmlns:android=
"http://schemas.android.com/apk/res/android"
android:id=
"@+id/container"
android:layout_width=
"match_parent"
android:layout_height=
"match_parent"
>
|
可以看到这是布局的根节点,比平时的布局文件多了一行代码:
1
|
xmlns:rain=
"http://schemas.android.com/apk/res/com.jikexueyuan.rain"
|
这是项目的包名。而自定义控件设置属性时,如下:
1
2
3
4
5
6
7
8
|
<com.jikexueyuan.rain.v2.RainView
android:layout_width=
"match_parent"
android:layout_height=
"match_parent"
android:background=
"#ff000000"
rain:rainColor=
"0xff00ff00"
rain:rainNum=
"50"
rain:randColor=
"true"
rain:size=
"20"
/>
|
而在代码中需要,改变属性时怎么操作呢,也是代码如下:
1
2
3
4
5
6
7
|
TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.RainView);
rainNum = ta.getInteger(R.styleable.RainView_rainNum,
80
);
size = ta.getInteger(R.styleable.RainView_size,
20
);
rainColor = ta.getInteger(R.styleable.RainView_rainColor,
0xffffffff
);
randColor = ta.getBoolean(R.styleable.RainView_randColor,
false
);
ta.recycle();
|
你会发现,TypedArray 类就用到了。 在引用时,还需要,注意的是:R.styleable.RainView, 而 设置属性时是这样的:R.styleable.RainView_randColor ,这是固定的命名方式。至此,TypedArray 类就讲完了。