以下示例中代码均在values/attrs.xml 中定义,属性均可随意命名。
1. reference:参考某一资源ID。
示例:
<declare-styleable name = "ruiyi">
<attr name = "background" format = "reference" />
<attr name = "src" format = "reference" />
</declare-styleable>
2. color:颜色值。
示例:
<declare-styleable name = "ruiyi">
<attr name = "textColor" format = "color" />
</declare-styleable>
3. boolean:布尔值。
示例:
<declare-styleable name = "ruiyi">
<attr name = "focusable" format = "boolean" />
</declare-styleable>
4. dimension:尺寸值。
示例:
<declare-styleable name = "ruiyi">
<attr name = "layout_width" format = "dimension" />
</declare-styleable>
5. float:浮点值。
示例:
<declare-styleable name = "ruiyi">
<attr name = "fromAlpha" format = "float" />
<attr name = "toAlpha" format = "float" />
</declare-styleable>
6. integer:整型值。
示例:
<declare-styleable name = "ruiyi">
<attr name = "frameDuration" format="integer" />
<attr name = "framesCount" format="integer" />
</declare-styleable>
7. string:字符串。
示例:
<declare-styleable name = "ruiyi">
<attr name = "text" format = "string" />
</declare-styleable>
8. fraction:百分数。
示例:
<declare-styleable name="ruiyi">
<attr name = "pivotX" format = "fraction" />
<attr name = "pivotY" format = "fraction" />
</declare-styleable>
9. enum:枚举值。
示例:
<declare-styleable name="ruiyi">
<attr name="orientation">
<enum name="horizontal" value="0" />
<enum name="vertical" value="1" />
</attr>
</declare-styleable>
10. flag:位或运算。
示例:
<declare-styleable name="ruiyi">
<attr name="windowSoftInputMode">
<flag name = "stateUnspecified" value = "0" />
<flag name = "stateUnchanged" value = "1" />
<flag name = "stateHidden" value = "2" />
<flag name = "stateAlwaysHidden" value = "3" />
</attr>
</declare-styleable>
11.多类型。
示例:
<declare-styleable name = "ruiyi">
<attr name = "background" format = "reference|color" />
</declare-styleable>
12.引用API变量。
示例:
<declare-styleable name="ruiyi">
<attr name="android:text1" />
<attr name="text2" format="string" />
</declare-styleable>
ta.getString(R.styleable.ruiyi_android_text)
获取属性时有一点点区别:
定义时:
1-11 存在属性的自定义name 和指定的类型(format)
12 引用系统属性时,仅仅只有name,不能重复指定类型
引用时:
所以类型获取都可以借助TypedArray 读取,以12属性为例
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.ruiyi);
String text1 = ta.getString(R.styleable.ruiyi_android_text1); //系统属性
<pre name="code" class="java"> String text2 = ta.getInteger(R.styleable.ruiyi_text2); //自定义属性
ta.recycle();
}
就这样