是的,addTextChangedListener的这个方法是可用的,但是我们必须 for each 我们想要转换成大写的Edittext实现这个方法.所以你对反向绑定适配器的了解是正确的.在InverserBinding Adapter中,我们必须一次性创建此方法,并且您可以多次使用它.
我已经使用BindingAdapter和InverseBinding Adapter实现了这一点.在一个Kotlin文件中,按如下方式编写这两个函数.
@BindingAdapter(value = ["setText", "custom:AttrChanged"], requireAll = false)
fun EditText.updateText(text: String?, listener: InverseBindingListener) {
if (this.text.toString() != text) {
this.setText(text)
}
this.doOnTextChanged { _: CharSequence?, _: Int?, _: Int?, _: Int? ->
listener.onChange()
}
}
@InverseBindingAdapter(attribute = "setText", event = "custom:AttrChanged")
fun EditText.getUpdatedText(): String? {
return this.text.toString().uppercase()
}
对于大写,我创建了一个字符串类型的MutableLiveData大写变量
var uppercase = MutableLiveData("")
现在,在XML中,我将该属性设置为:
<androidx.appcompat.widget.AppCompatEditText
android:id="@+id/edit_txt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="30dp"
setText="@={viewModels.uppercase}"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/btn_login_data_binding" />