I want to create a custom class that takes a color as one of its attributes when laid out in an Android XML file. However, a color could be a resource or it could be one of a number of direct color specifications (eg a hex value). Is there a simple preferred method for using AttributeSet
to retrieve the color, since an integer representing a color could refer either to a resource value or an ARGB value?
Let's say you have defined your custom color attribute like this:
<declare-styleable name="color_view">
<attr name="my_color" format="color" />
</declare-styleable>
Then in the constructor of your view, you can retrieve the color like this:
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();
}
}
You don't actually have to worry how the color attribute was populated, either like this
<com.test.ColorView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:my_color="#F00"
/>
or like this:
<com.test.ColorView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:my_color="@color/red"
/>
The getColor
method will return a color value in any case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With