1:自定义属性属性值类型
1、reference 引用类型值 : @id/...
2、 color 颜色类型值 #ff00ff
3、 boolean 布尔类型值 true , false
4、 dimension 尺寸类型值 dp / px /sp
5、 integer 整数类型值 weight progress max
6、float 浮点型值 0.1f
7、string 字符串类型值 "atrrs"
8、<enum> 枚举类型值 :水平/垂直
9、 flag:位或运算
10、fraction:百分数
使用步骤:
一、定义属性: 在values目录下创建attrs.xml
<declare-styleable name="suibianxue">
<attr name="roundColor" format="color"></attr>
<attr name="textColor" format="color"></attr>
<attr name="roundWidth" format="dimension"></attr>
<attr name="textSize" format="dimension"></attr>
</declare-styleable>
<declare-styleable name="GitvImageView"> <attr name="loadingRes" format="reference" /> </declare-styleable>
<declare-styleable name="AlignTextView"> <attr name="align" format="enum"> <enum name="left" value="0"/> <enum name="center" value="1"/> <enum name="right" value="2"/> </attr> </declare-styleable>
<declare-styleable name="ZoomLayout"> <attr name="zoomStyle"> <flag name="equality" value="0" /> <flag name="dynamic" value="1" /> </attr> <attr name="zoomWhen"> <flag name="focus" value="0" /> <flag name="selected" value="1" /> </attr> <attr name="zoomX" format="dimension" /> <attr name="zoomY" format="dimension" /> <attr name="scaleX" format="float" /> <attr name="scaleY" format="float" /> <attr name="zoomEnable" format="boolean" /> </declare-styleable>
二、 在使用了自定义属性的xml布局文件中引用当前应用的命名空间:
xmlns:app="http://schemas.android.com/apk/res-auto"
三、 在自定义视图标签中使用自定义属性
app:scaleY="1.1" app:zoomStyle="equality"
四、在自定义View类的构造方法中, 取出布局中的自定义属性值
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.GitvImageView); int loadingRef = typedArray.getResourceId(R.styleable.GitvImageView_loadingRes, -1);
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ZoomLayout, defStyleAttr, 0); mZoomStyle = a.getInt(R.styleable.ZoomLayout_zoomStyle, 0); mZoomWhen = a.getInt(R.styleable.ZoomLayout_zoomWhen, -1); mScaleX = a.getFloat(R.styleable.ZoomLayout_scaleX, 1.0f); mScaleY = a.getFloat(R.styleable.ZoomLayout_scaleY, 1.0f); mZoomX = a.getDimension(R.styleable.ZoomLayout_zoomX, 0.0f); mZoomY = a.getDimension(R.styleable.ZoomLayout_zoomY, 0.0f); mZoomEnable = a.getBoolean(R.styleable.ZoomLayout_zoomEnable, true); a.recycle();