如何解决三元运算符的Android双向数据绑定问题必须恒定
我的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{}
块中)。
这是我收到的错误:
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
函数: 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
- 仅在使用
BindingAdapter
和自定义属性“同时” 时触发EditText
函数。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。