微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用Android上的数据绑定设置文本颜色

我正在尝试使用数据绑定库设置TextView文本颜色
android:textColor="@{holder.getTitleColor(context,item)}"

Holder类中的方法定义如下

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

无论我是否返回颜色int(@ColorInt)或颜色资源(@ColorRes),它都会将文本绘制为纯白色.我究竟做错了什么?

解决方法

我似乎提供的int被解释为十六进制颜色,即使这个setter应该期望资源ID看起来很直观.

使用为每个可绑定视图生成的Context参考,并使用它将资源ID转换为您指向的颜色,如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().

用它来设置这样的颜色:

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐