有时候我们自定义的view需要用到有自己定义的属性。
首先定义自己的属性,在res/values/attrs.xml中定义,xml文件如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name = "myView">
<attr name = "text" format = "string" />
<attr name = "textSize" format = "dimension"/>
<attr name = "textColor" format = "color"/>
<attr name = "rectColor" format = "color"/>
</declare-styleable>
</resources>
name属性很重要,关系到以后的调用。
format为属性的类型,这里列举了几种基本的数据类型,注意textSize等关系到大小的属性格式为dimension。
在布局文件中的使用。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:my="http://schemas.android.com/apk/res/com.example.myview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
>
<com.example.myview.MyView
android:layout_width="100dp"
android:layout_height="100dp"
my:text = "点击开始计数"
my:textColor = "#ffff0000"
my:textSize = "21sp"
my:rectColor = "#ff00ff00"
/>
</RelativeLayout>
xmlns:my="http://schemas.android.com/apk/res/com.example.myview"
为使用(建议包名改写成res-auto)
my字段调用自定义属性的关键代码。
获取属性值对自定view进行初始化。
//获取xml文件中的属性数组
private void initAttrs(AttributeSet attrs) {
mPanit = new Paint();
mBound = new Rect();
setOnClickListener(this);
//和attr.xml中的属性列表对应上
TypedArray ta = getContext().obtainStyledAttributes(attrs,R.styleable.myView);
String text = ta.getString(R.styleable.myView_text);
setText(text);
int textSize = ta.getDimensionPixelOffset(R.styleable.myView_textSize, 26);
setTextSize(textSize);
int color = ta.getColor(R.styleable.myView_textColor, 0xff000000);
setTextColor(color);
int rectColor = ta.getColor(R.styleable.myView_rectColor, 0xff000000);
setRectColor(rectColor);
ta.recycle();
}
AttributeSet attrs为xml中的属性和它所对应的值。
TypedArray ta = getContext().obtainStyledAttributes(attrs,R.styleable.myView);
只获取自定义属性名为myView中的属性。并且赋值给TypeArray ta。
之后便可根据 ta 获取获取对应的属性值了。
至于获取的属性值该怎么用,就要看你自己的了。