Android custom view attributes - 'color' a

2019-08-09 09:52发布

问题:

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.