Android三元运算符的双向数据绑定问题必须是常量

Android Two Way DataBinding Problem of Ternary Operator Must be Constant

我的EditText是这样的:

<EditText
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="2"
    android:text="@={viewModel.isAddCase? ``: `` + viewModel.currentStudent.age}"    //problem here
    android:inputType="number" />

我希望 EditText 不显示基于 isAddCase 变量的任何内容(空字符串),该变量是 MutableLiveData<Boolean>ViewModel [=40 时初始化的=] 对象被创建(在 init{} 块内)。

这是我得到的错误:

The expression '((viewModelIsAddCaseGetValue) ? ("") : (javaLangStringViewModelCurrentStudentAge))' cannot be inverted, so it cannot be used in a two-way binding

Details: The condition of a ternary operator must be constant: android.databinding.tool.writer.KCode@37a418c7

更新

即使这样也不起作用,显示相同的错误:

android:text="@={viewModel.currentStudent.age == 0? ``: `` + viewModel.currentStudent.age}"

我想三元运算在双向运算中效果不佳 DataBinding

您需要删除起始花括号前的等号

android:text="@{viewModel.isAddCase ? ``: `` + viewModel.currentStudent.age}"    

您也可以使用 String.valueOf 代替 ``

android:text="@{viewModel.isAddCase ? ``: String.valueOf(viewModel.currentStudent.age)}"    

好的,经过这几天我想出了完美的解决方案:

1.创建BindingAdapter函数:

object DataBindingUtil {                                    //place in an util (singleton) class
    @BindingAdapter("android:text", "isAddCase")            //custom layout attribute, see below
    @JvmStatic                                              //required
    fun setText(editText: EditText, text: String, isAddCase: Boolean) {     //pass in argument
        if (isAddCase) editText.setText("") else editText.setText(text)
    }
}
  • 将多个参数从布局传递到 BindingAdapter 函数:

2。在 View 中应用自定义属性:

<EditText
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="2"
    android:inputType="number"
    android:text="@={`` + viewModel.currentStudent.age}"        //two-way binding as usual
    app:isAddCase="@{viewModel.isAddCase}" />                   //here

  • 只有在使用EditText和自定义属性同时.
  • 时才会触发BindingAdapter函数