Search code examples
androidandroid-databinding

Set text color using data binding on Android


I'm trying to set TextView text color using data binding library

android:textColor="@{holder.getTitleColor(context, item)}"

where the method in Holder class is defined like below

public int getTitleColor(Context context, Item item) {
   ...
}

No matter if I return color int (@ColorInt) or color resource (@ColorRes) it paints the text solid white. What am I doing wrong?


Solution

  • I seems the int you are providing is interpreted as a hex color, even though it seem intuitive that this setter should be expecting a resource ID.

    use the Context reference generated for each bindable view, and use it to convert the resource ID to the color you are pointing to, as described in the DataBinding Dev Guide:

    A special variable named context is generated for use in binding expressions as needed. The value for context is the Context from the root View's getContext().

    use it to set color like this:

     <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@{data.text}"
                android:textColor="@{context.getColor(data.colorRes)}"
                />
    

    Edit

    for backwards compatibility you can use ContextCompat. Import needed:

    <layout>
        <data>
            <import type="android.support.v4.content.ContextCompat"/>
            <variable name="data" type="com.whatever.myapp.MyModel"/>
            ...
        </data>
        ...
         <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@{data.text}"
                android:textColor="@{ContextCompat.getColor(context, data.colorRes)}"
                />
    </layout>