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