Android 可绘制对象上的数据绑定

Android data binding on drawable

我有两个形状可绘制对象,rounded_corners.xml 和 rounded_corners_red.xml,它们将分别用于显示有效文本输入和无效文本输入。

我希望在用户单击登录按钮时动态设置此 drwable,这样如果有效文本显示 rounded_corners.xml,如果无效显示 rounded_corners_red.xml。

下面是我如何将它放入我的布局中 xml。

<EditText android:id="@+id/et_ip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@={systemSettings.isValid ? @drawable/rounded_corners : @drawable/rounded_corners_red}"
android:text="@={systemSettings.serverIP, default=@string/ip_host}"
android:textColor="#000000" />

我希望根据我的模型中定义的 isValid 可观察变量动态应用可绘制对象 class。 我的代码编译没有错误。但它给出 运行 时间错误

java.lang.RuntimeException: Found data binding errors.
****/ data binding error ****msg:The expression ((systemSettingsIsValidGet) ? (getDrawableFromResource(etIp, R.drawable.rounded_corners)) : (getDrawableFromResource(etIp, R.drawable.rounded_corners_red))) cannot cannot be inverted: The condition of a ternary operator must be constant: android.databinding.tool.writer.KCode@429a75fd
file:D:xxx\app\src\main\res\layout\fragment_system_settings.xml
loc:92:47 - 92:128
****\ data binding error ****

有人知道为什么会这样吗? 谢谢

您的声明是双向绑定@={}

@={systemSettings.isValid ? @drawable/rounded_corners : @drawable/rounded_corners_red}`

这就是为什么您发现错误指出表达式

cannot cannot be inverted

甚至直接告诉你原因:

The condition of a ternary operator must be constant

但是由于您只是获取可绘制资源,因此只需从表达式中删除 = 即可。