【发布时间】:2019-02-01 11:59:36
【问题描述】:
我正在尝试使用像这样的类将实时数据与TextInputLayout 的数据绑定一起使用:
class MutableLiveDataWithErrorText<T> : MutableLiveData<T>() {
val errorText = MutableLiveData<String>().apply { value = "" }
}
现在,当尝试将其用于 xml 中的错误文本时,
<layout>
<data>
<!-- ... -->
<variable
name="target"
type="com.my.app.MutableLiveDataWithErrorText<String>" />
</data>
<com.google.android.material.textfield.TextInputLayout
app:errorEnabled="true"
app:errorText="@{target.errorText}">
<!-- ... -->
</com.google.android.material.textfield.TextInputLayout>
</layout>
我收到此错误:
Cannot find getter 'getErrorText' for type String.
我尝试创建一个 BindingAdapter 来解决这个问题:
@BindingAdapter("errorTextLive")
fun setErrorTextLive(
view: TextInputLayout,
liveDataWithErrorText: MutableLiveDataWithErrorText<String>
) {
if (liveDataWithErrorText.errorText.value.isNullOrEmpty().not()) {
view.error = liveDataWithErrorText.errorText.value
}
}
将 xml 赋值改为:
app:errorTextLive="@{target}"
这使得编译成功,但不再观察到target.errorText的变化,而是观察target的变化,仅当target的值发生变化时更新errorText。
有没有办法让它遵守target.errorText?
【问题讨论】:
标签: android kotlin android-databinding android-livedata