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

标签 android data-binding colors resources android-databinding

是否可以使用 android 数据绑定(bind)从 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。它们在数据绑定(bind)中成为相同的 inputValue 字段。如果您设置自定义颜色,这只是一个问题。来自 Google 的错误,应在下一次更新中修复。

最佳答案

是的,你可以引用颜色:

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

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

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

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

关于来自资源的android数据绑定(bind)颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43752443/

相关文章:

android - 在运行时更改 9-patch 图像颜色android

android - 在 android.widget.ImageView 上找不到参数类型为 int 的属性 'android:layout_width' 的 setter

javascript - 2.2.0 版本异常键触发的 knockout.js 值绑定(bind)

Grails 与语言环境无关的十进制数据绑定(bind)

performance - 对于那些使用 SubSonic 的人,您在大型应用程序中看到了什么样的性能?

r - R Shiny 应用程序的本地版本和shinyapps.io 版本之间的颜色不同

javascript,在开始颜色和结束颜色之间选择一个随机的十六进制颜色

android - OnTouchListerner 不应将打开 DrawerLayout 的滑动解释为长按

android - IntelliJ Idea 中的谷歌地图

java - Android 应用内结算 v3. onActivityResult