一,属性介绍
format 格式类型
"reference" //引用
"color" //颜色
"boolean" //布尔值
"dimension" //尺寸值
"float" //浮点值
"integer" //整型值
"string" //字符串
"fraction" //百分数,比如200%
枚举型的格式: format的格式,视value的值而定
< attr name="attrtest">
< enum name="horizontal" value="0" />
< enum name="vertical" value="1" />
< /attr>
标志位、位或运算,格式如下:
< attr name="windowSoftInputModeTest">
< flag name = "stateUnspecified" value = "0" />
< flag name = "stateUnchanged" value = "1" />
< flag name = "stateHidden" value = "2" />
< flag name = "stateAlwaysHidden" value = "3" />
< flag name = "stateVisible" value = "4" />
< flag name = "stateAlwaysVisible" value = "5" />
< flag name = "adjustUnspecified" value = "0x00" />
< flag name = "adjustResize" value = "0x10" />
< flag name = "adjustPan" value = "0x20" />
< flag name = "adjustNothing" value = "0x30" />
< /attr>
二,attr文件的创建,以及在布局文件xml中的使用
1、在资源文件夹(values)中新建文件名称为 attr.xml 的资源文件
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- declare-styleable 为规定写法,不可改 -->
<!-- name="MyView" name可任意填写 -->
<!-- 下面定义了,字体颜色,字体大小,枚举的gravity属性 -->
<declare-styleable name="MyView">
<attr name="textColor" format="color" />
<attr name="textSize" format="dimension" />
<attr name="gravity" >
<enum name="left" value="0" />
<enum name="right" value="1" />
<enum name="center_horizontal" value="2" />
</attr>
</declare-styleable>
</resources>
2、在布局文件xml中,使用自定义属性
引用:xmlns:test=”http://schemas.android.com/apk/res/com.arlos.attrstest”
test是随便写的.后面的包名是你所在的项目的根包.也就是在manifest里的com.arlos.attrstest
package="com.arlos.attrstest "
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:test="http://schemas.android.com/apk/res/com.arlos.attrstest"//一定记得添加前缀
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<com.hml.demo.MyView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
test:gravity="center_horizontal"
test:textSize="20px"//test是个前缀 test:textSize="20px"需要全部手打,其他俩个也是手打
test:textColor="#ffffff"/>
</LinearLayout>
三、自定义View中的解析,获取布局文件中传入的参数值。
private void init(Context context,AttributeSet attrs) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.flowLayout);
int textColor = a.getColor(R.styleable.MyView_textColor, 0XFFFFFFFF);
float textSize = a.getDimension(R.styleable.MyView_textSize, 36);
int flagGravity = a.getInteger(R.styleable.MyView_gravity, 0);
a.recycle();//释放
}
PS: 在解析枚举类型的 gravity 属性时,使用的方法a.getInteger,视values的值而定,本测试例子可以使用
a.getInteger(R.styleable.MyView_gravity, 0);方法直接获取到 int 型的数据,默认值为 0,用于之后的比较,我们也可以使用String flagGravity2 = a.getString(R.styleable.MyView_gravity); 直接获得字符串的方式,具体看需求。
总结:
至此,自定义view的自定义属性已经介绍完,大家可以举一反三,尝试一下其他数据类型,若有不对之处,还请各位指出。
简单的说,自定义view属性就是,在attr的资源文件创建一个xml个数的数据,在布局文件使用,在自定义view的构造函数中去解析。
其实,有时候简单的自定义view其实没必要写自定义属性,一来使用不方便,二来,自定义view的代码会增加,简单的view在自定义view内部修改即可,注释写清楚,相信其他人修改起来也很方便。
本文借鉴此文:http://blog.csdn.net/jiangwei0910410003/article/details/17006087