自定义属性参数介绍(属性定义可以多种同时使用)
- reference:参考某一资源ID。
- color:颜色值。
- boolean:布尔值。
- dimension:尺寸值。
- float:浮点值。
- integer:整型值。
- string:字符串。
- fraction:百分数。
- enum:枚举值。
- flag:位或运算。
以上属性在attrs文件下定义
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyTextView">
<attr name="header" format="reference"/>
<attr name="headerHeight" format="dimension"/>
<attr name="headerVisibleHeight" format="dimension"/>
<attr name="age">
<flag name="child" value="10"/>
<flag name="young" value="18"/>
<flag name="old" value="60"/>
</attr>
</declare-styleable>
</resources>
在xml中使用这些自定义属性:
- 在头部添加 xmlns:attrstest=”http://schemas.android.com/apk/res-auto” (attrstest这个名称可以随意命名)
- 代码中获取自定义属性的值:
通过obtainStyledAttributes方法得到TypedArray,注意最后记得回收这个TypedArray。代码如下:
TypedArray types = context.obtainStyledAttributes(attrs,
R.styleable.MyTextView);
int count = attrs.getAttributeCount();
for(int i = 0;i < count;i++){
int attr = types.getIndex(i);
switch (attr){
case R.styleable.MyTextView_header:
break;
case R.styleable.MyTextView_headerHeight:
float headerHeight = types.getDimension(attr,-1);
break;
case R.styleable.MyTextView_headerVisibleHeight:
break;
case R.styleable.MyTextView_age:
break;
}
}
types.recycle();
以上是最基本的介绍,更多功能后续探讨