I would like to define what color should be used when painting to a canvas depending on a custom state. This is how far I got:
In res/layout/content.xml:
<com.example.package.MyView
app:primary_color="@drawable/my_selector"
/>
primary_color is a custom attribute defined in res/values/attrs.xml:
<resource>
<declare-styleable name="MyView">
<attr name="primary_color" format="reference"/>
</declare-styleable>
</resource>
my_selector is defined in res/drawable/my_selector.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res/com.example.package">
<item
app:state_a="true"
android:drawable="@drawable/red" />
<item
app:state_b="true"
android:drawable="@drawable/orange" />
<item
app:state_c="true"
android:drawable="@drawable/red" />
</selector>
red, orange and red are defined in res/values/colordrawable.xml:
<resources>
<drawable name="red">#f00</drawable>
<drawable name="orange">#fb0</drawable>
<drawable name="green">#0f0</drawable>
</resources>
In MyView I can get this drawable:
StateListDrawable primaryColor;
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
try{
primaryColor = (StateListDrawable) a.getDrawable(
R.styleable.MyView_primary_color);
}finally {
a.recycle();
}
}
primaryColor updates correctly with the different states, I can test this by calling:
setBackground(primaryColor);
But I want to use this color with Paint, like this:
paint.setColor(primaryColor);
But this is obviously not allowed. I've tried converting the primaryColor to a ColorDrawable which has the method getColor(), but I can't figure out how to do this, if it is possible.
Any suggestions on how to get the color that can be used in the the view from a selector would be amazing.
I found ColorStateList which turned out to be exactly what I needed. The following is a simplified version of my current implementation, in case someone else gets in the same rut as I did.
In res/color/my_selector.xml
In res/layout/content.xml (This has another layout wrapped around it, but that is not relevant)
primary_color is defines as a reference in res/values/attrs.xml
I get the reference to the ColorStateList in the constructor of MyView:
When I want to get the color for the current state:
If you implement a custom state, like I did, then you will also have to override onCreateDrawableState for the states to actually update, but there is plenty of documentation/posts that cover that.