I've got in attrs.xml
<resources>
<!-- theme specific colors -->
<attr format="reference|color" name="foreground" />
<attr format="reference|color" name="background" />
</resources>
And then in theme.xml
<style name="MyTheme" parent="android:Theme.Black">
<item name="android:windowNoTitle">true</item>
<item name="foreground">#0000FF</item>
<item name="background">#00FF00</item>
</style>
I also created color selector named forground_to_background.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="?background"/> <!-- pressed -->
<item android:state_focused="true" android:color="?background"/> <!-- focused -->
<item android:color="?foreground"/> <!-- default -->
</selector>
Now I'd like to use it all together in TextView:
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/forground_to_background" />
Unfortunately it doesn't work. Instead of having nice green blue colors I've got only one color - red. TextView is always red. When I change TextView to use "?foreground" color will change. Also when I change in colors selector from "?xxxx" to hardcoded value as "#00f" color start to work.
Where is problem? What am I doing wrong?
Edit: I believe it is duplicate of problem/bug Can a selector resource use a color defined in a style?
Edit2: Moreover when I try use this TextView in ListView application crashes. It cannot parse XML.
You cannot reference ?attr/ when choosing colors for a selector. What you can do, if you want per-theme colors in your selector, is create multiple selectors which reference @color/ and @drawable/, and then have a "reference" attr which associates one of the selectors with the given style.
<attr name="forground_to_background" format="reference" />
You then have to set the text color like
android:textColor="?attr/forground_to_background"
I believe the text was always red because Android was interpreting the attr's integer value as a color (red), rather than using it as a lookup for what you actually wanted.
The reason why this happens is that I have different Context. While inflating Context is aware of my theme attrs, but to the ListView adapter I passed ApplicationContext that wasn't aware of those attrs. Now I don't know why it doesn't know about them ;)
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