Android自定义视图属性-不允许使用“颜色"作为属性名称 [英] Android custom view attributes - 'color' as attribute name disallowed
问题描述
我已经制作了一个简单的自定义视图,即"ColorSwatch".它是圆形的,显示分配的颜色,如果该颜色具有透明性,则将该颜色绘制在检查图案的顶部.视图工作正常.
I've made a simple custom view, a "ColorSwatch". It's circular, shows the assigned color and if that color has transparency, the color is drawn atop a checker pattern. The view works fine.
我的问题是,当我为色板定义自定义属性(在values/attrs_color_swatch_view.xml
中)时,无法指定名为"color"的属性.编译器抱怨已经定义了颜色,并把我指向了colors.xml文件.作为解决方法,我调用了参数swatchColor
,但我希望它只是color
.
My problem is that when I define the custom attributes for the swatch (in values/attrs_color_swatch_view.xml
), I can't specify an attribute named "color". The compiler complains that color is already defined, and points me to my colors.xml file. As a workaround, I called the parameter swatchColor
, but I'd prefer it to simply be color
.
文件:values/attrs_color_swatch_view.xml
<resources>
<declare-styleable name="ColorSwatchView">
<attr name="swatchColor" format="color"/><!-- would prefer to simply be 'color', not 'swatchColor' -->
<attr name="selectionThickness" format="dimension"/>
<attr name="isSelected" format="boolean"/>
<attr name="selectionColor" format="color"/>
<attr name="alphaCheckerSize" format="dimension" />
</declare-styleable>
</resources>
是否可以使用属性名称color
?还是保留关键字?在我看来,有什么方法可以对其命名空间吗?
Is there a way to use the attribute name color
? Or is it a reserved keyword? Is there a way to namespace it somehow to my view?
推荐答案
出于与不能使用background
相同的原因,您不能使用color
.它们已经在android名称空间中定义.
You can't use color
for the same reason you can't use background
. They are already defined in the android namespace.
那么如何使用color
或任何其他保留的属性名称?通过使用已定义的内容,而不创建新的内容.
So how to use color
or any other attribute name that's reserved ? By using the ones that's already defined, and not creating new ones.
而不是:
<attr name="swatchColor" format="color"/>
使用此:
<attr name="android:color"/>
始终确保您使用android提供的功能.只有在您认为它不适合您的需求时,才继续创建您自己的属性.
Always make sure that you use the ones supplied by android. Only if you think it doesn't suit your needs, go ahead and create your own attribute.
这篇关于Android自定义视图属性-不允许使用“颜色"作为属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!