How can I reliably get color from an AttributeSet?

I want to create a custom class that accepts color as one of its attributes if it is laid out in an Android XML file. However, a color may be a resource or may be one of several direct color specifications (e.g., a hexadecimal value). Is there a simple preferred method for using an AttributeSet to extract color, since an integer representing a color can refer to either a resource value or an ARGB value?

+7
source share
1 answer

Let's say you define your own color attribute as follows:

 <declare-styleable name="color_view"> <attr name="my_color" format="color" /> </declare-styleable> 

Then in the constructor of your view, you can get the color as follows:

 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(); } } 

In fact, you don’t have to worry about how the color attribute was added, for example 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 the color value anyway.

+22
source

All Articles