Android custom view attributes - 'color' as attribute name disallowed

喜你入骨 提交于 2019-12-11 13:52:45

问题


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.

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.

The file: 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>

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?


回答1:


You can't use color for the same reason you can't use background. They are already defined in the android namespace.

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.

Instead of :

<attr name="swatchColor" format="color"/>

use this:

<attr name="android:color"/>

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.



来源:https://stackoverflow.com/questions/33699561/android-custom-view-attributes-color-as-attribute-name-disallowed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!