Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reliably get a color from an AttributeSet?

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?

like image 421
Andrew Wyld Avatar asked Nov 22 '12 12:11

Andrew Wyld


1 Answers

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.

like image 68
sdabet Avatar answered Nov 03 '22 01:11

sdabet