androidandroid-databindingtextcolorandroid-selectorandroid-text-color

Databinding and ColorStateList Selector


I have a recycler view which I need to use one of the color selectors, depending on what value in the data binding, to change the TextView color.

I have two selectors:

color/selector_item_text.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/white" android:state_checked="true" />
    <item android:color="@color/white" android:state_pressed="true" />
    <item android:color="@color/white" android:state_activated="true" />
    <item android:color="@color/black" />
</selector>

color/selector_item_textwithspecial.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/pink" android:state_checked="true" />
    <item android:color="@color/pink" android:state_pressed="true" />
    <item android:color="@color/pink" android:state_activated="true" />
    <item android:color="@color/orange" />
</selector>

And I'm binding it to my TextView like this:

<TextView android:text="@{data.displayPrice}"
    android:textColor="@{data.isSpecial ? @color/selector_item_textwithspecial : @color/selector_item_text}"
    style="@style/ProductPrice"/>

The problem is that the TextView color is always orange (if it has special) or black. The selection never changes the color. However, if I remove the databinding, it worked as expected.

For example, the following will make TextView becomes pink (when selected) and orange (when not selected)

<TextView android:text="@{data.displayPrice}"
    android:textColor="@color/selector_item_textwithspecial"
    style="@style/ProductPrice"/>

Any idea how to tackle this problem?

Thanks...


Solution

  • Figured it out, see here

    use android:textColor="@{data.isSpecial ? @colorStateList/selector_item_textwithspecial : @colorStateList/selector_item_text}"