我想创建一个自定义类,在 Android XML 文件中布局时将颜色作为其属性之一。然而,颜色可以是一种资源,也可以是多种直接颜色规范之一(例如十六进制值)。有没有一种简单的首选方法来使用AttributeSet
检索颜色,因为表示颜色的整数可以引用资源值或 ARGB 值?
假设您已经像这样定义了自定义颜色属性:
<declare-styleable name="color_view">
<attr name="my_color" format="color" />
</declare-styleable>
然后在视图的构造函数中,您可以像这样检索颜色:
public ColorView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.color_view);
try {
int color = a.getColor(R.styleable.color_view_my_color, 0);
setBackgroundColor(color);
} finally {
a.recycle();
}
}
您实际上不必担心颜色属性是如何填充的,就像这样
<com.test.ColorView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:my_color="#F00"
/>
或者像这样:
<com.test.ColorView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:my_color="@color/red"
/>
The getColor
任何情况下方法都会返回一个颜色值。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)