0
我使用數據綁定在我的Android應用程序,我想改變字體顏色取決於我的模型處於什麼狀態。喜歡的東西使用Android數據綁定時可以有動態資源路徑嗎?
android:textColor='@{@color/state_ + myobj.state}'
。而
<color name="state_good">#0f0</color>
。是這樣的可能嗎?
我使用數據綁定在我的Android應用程序,我想改變字體顏色取決於我的模型處於什麼狀態。喜歡的東西使用Android數據綁定時可以有動態資源路徑嗎?
android:textColor='@{@color/state_ + myobj.state}'
。而
<color name="state_good">#0f0</color>
。是這樣的可能嗎?
我能想到的兩個主要的可能性。
,你可能不希望一個是讓你的模型對象有一個返回的顏色資源ID(根據其狀態)getter方法。雖然這很簡單,但它會違反典型的視圖/模型分離問題,因爲模型不應該關心渲染顏色。
另一種是具有一個工具類某處,具有靜態方法,給定的狀態下,返回顏色資源ID。然後,您可以將該類導入<layout>
並從表達式中調用它。
例如,這種佈局進口Html
,要能夠調用Html.fromHtml()
,以處理可能具有HTML格式的字符串(或者,在這種情況下,HTML實體):
<?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>
在你的情況,你將導入您的實用程序類,並呼籲在android:textColor
屬性您static
方法。
即興,冥冥中,給定的狀態,返回顏色資源ID創建一個靜態實用方法,並使用它。所以,'機器人:文字顏色= 「@ {Util.gimmeColor(myobj.state)}」',或一些這樣的。 – CommonsWare
@CommonsWare完美的作品。謝謝! – rosegrink