我的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
变量的任何内容(空字符串),该变量是在创建ViewModel
类对象时启动的MutableLiveData<Boolean>
(在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
好的,经过这些天,我已经找到了完美的解决方案:
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
函数: 使用 Android 数据绑定时,如何通过 xml 为自定义资源库传递多个参数
阿拉伯数字。在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
函数。