android 来自资源的数据绑定颜色

android data binding colors from resources

是否可以使用 android 的数据绑定来引用来自 xml 的颜色?

这很好用:

android:textColor="@{inputValue == null ? 0xFFFBC02D : 0xFFFFEB3B}"

但这不是:

android:textColor="@{inputValue == null ? @color/red : @color/blue}"

在此处报告:https://issuetracker.google.com/issues/38021292

* 编辑 *

事实证明,这只是和 id 问题/错误,仅在边缘情况下弹出。我的 xml:

    <TextView
        android:id="@+id/input_value"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@{inputValue}"
        android:textColor="@{showAsEmpty ? @color/registerInputEmpty : @color/registerInputSet}"
        tools:text="Select to edit"/>

它的问题在于 inputValue 参数和 input_value id。它们在数据绑定中成为相同的 inputValue 字段。如果您设置自定义颜色,这只是一个问题。来自 Google 的错误应在下次更新中修复。

你可以的:)

android:textColor="@{inputValue == null ? R.color.red: R.color.blue}"

是的,你可以参考颜色:

<TextView android:textColor="@{inputValue == null ? @color/red : @color/blue}" .../>

颜色资源作为整数加载。如果您的属性需要一个 Drawable 并接收一个整数,它会被转换为一个 ColorDrawable。例如:

<View android:background="@{hasError ? @color/errorBg : @color/normalBg}" .../>

如果一定要引用资源ID,请使用R值并记得导入R。这种情况并不常见,但有些setter采用资源ID而不是值。这在框架视图中并不常见,因为通常有 setter 获取资源值和资源 ID,但您可能会在自定义视图中找到它。

这是一个 google 错误:id 和参数不能同名:参数 inputValue 和视图 id @id/input_value。它们在数据绑定中成为相同的 inputValue 字段。如果您设置自定义颜色,这只是一个问题。来自 Google 的错误应在下次更新中修复。