如何解决根据其他视图的属性启用视图-android databinding
我有一个TextInputLayout,其错误已启用,并且根据某些原因,错误被禁用。问题是我禁用了一个按钮,但是当另一个视图的错误消失时我想启用它。您知道使用数据绑定的工作原理吗?谢谢。我的代码是此代码,但是对错误启用/禁用更改没有反应。
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/layout1"
app:errorTextAppearance="@style/errorText"
app:errorEnabled="true"
style="@style/outlinedTextInputLayout.Dense">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/name"
style="@style/outlinedTextInputEditText.Multilines"
android:hint="@string/name"
android:text="@={viewModel.name}"/>
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.button.MaterialButton
android:id="@+id/acceptBtn"
android:onClick="@{() -> viewModel.accept()}"
android:enabled="@{!name.isErrorEnabled()}"
style="@style/materialButton.Text"
android:text="@string/str_accept" />
解决方法
如果我理解正确,那么您希望基于文本更改启用或禁用按钮,如果是,则执行以下操作。
创建绑定适配器以设置像这样的文本观察器。
@BindingAdapter("textChangedListener")
@JvmStatic
fun addOnTextChangedListener(textView: TextInputEditText,listener: TextWatcher) {
autoCompleteTextView.addTextChangedListener(listener)
}
秒,在这样的布局中传递侦听器。 app:addTextChangedListener="@{viewModel.nameWatcher}"
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/layout1"
app:errorTextAppearance="@style/errorText"
app:errorEnabled="true"
style="@style/outlinedTextInputLayout.Dense">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/name"
style="@style/outlinedTextInputEditText.Multilines"
android:hint="@string/name"
app:addTextChangedListener="@{viewModel.nameWatcher}"
android:text="@={viewModel.name}"/>
</com.google.android.material.textfield.TextInputLayout>
在您的视图模型中创建文本观察器,并在文本更改后立即检查文本有效性,并使用某些 MutableLiveData 或 ObservableBoolean
启用和禁用按钮val nameWatcher = object :TextWatcher {
override fun afterTextChanged(s: Editable?) {
//here change button enable disable using some mutable live data or observable boolean
}
override fun beforeTextChanged(s: CharSequence?,start: Int,count: Int,after: Int) {}
override fun onTextChanged(s: CharSequence?,before: Int,count: Int) {}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。