Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android color selector doesn't work with custom attributes

Tags:

android

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.

like image 350
Mikooos Avatar asked Jan 25 '12 15:01

Mikooos


2 Answers

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.

like image 116
gelakinetic Avatar answered Nov 11 '22 19:11

gelakinetic


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

like image 22
Mikooos Avatar answered Nov 11 '22 17:11

Mikooos