我的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
时初始化创建类对象(在 init{}
block 内)。
这是我得到的错误:
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
.
最佳答案
好吧,这几天我已经找到了完美的解决方案:
<强>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
函数: How can I pass multiple arguments via xml for a custom setter when using Android data binding
<强>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
函数。
关于Android 双向数据绑定(bind) 三元运算符必须恒定的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64596538/