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.
fiddler
source share