I am using data-binding in my Android application, and I want to change the font color depending on what state my model is in. Something like
android:textColor='@{@color/state_ + myobj.state}'
in my layout. And
<color name="state_good">#0f0</color>
in my colors.xml. Is something like this possible?
I can think of two main possibilities.
The one that you probably don't want is to have your model object have a getter method that returns the color resource ID (based on its state). While this is simple, it would violate your typical view/model separation of concerns, as the model shouldn't really care about rendering colors.
The other is to have a utility class somewhere, with a static method that, given the state, returns the color resource ID. You can then import that class into the <layout>
and call it from the expression.
For example, this layout imports Html
, to be able to call Html.fromHtml()
, to handle strings that may have HTML formatting (or, in this case, HTML entities):
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<import type="android.text.Html"/>
<variable
name="item"
type="com.commonsware.android.databind.basic.Item"/>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="@+id/icon"
android:layout_width="@dimen/icon"
android:layout_height="@dimen/icon"
android:layout_gravity="center_vertical"
android:contentDescription="@string/icon"
android:padding="8dip"/>
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|center_vertical"
android:text="@{Html.fromHtml(item.title)}"
android:textSize="20sp"/>
</LinearLayout>
</layout>
In your case, you would import your utility class and call your static
method in the android:textColor
attribute.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.