addTextChangedListener监听输入变化的时候,会调用自定义的setEditText方法,如此会造成死循环,只能设置flag停止onChange()的调用,停止后addTextChangedListener方法的循环中断,当判断有新的文本输入时,继续执行文本的设置
@BindingAdapter("android:bindText")
fun setEditText(edit: TextAndEditView, str: String?) {
if (str == null) {
return
}
edit.editView.setText(str)
flag = false
oldCount = 0
}
@InverseBindingAdapter(attribute = "android:bindText", event = "android:contentAttrChanged")
fun getEditText(edit: TextAndEditView): String {
return edit.editView.text.toString()
}
@BindingAdapter(value = arrayOf("android:contentAttrChanged"))
fun setChangeListener(edit: TextAndEditView, listener: InverseBindingListener?) {
var simpleTextWatcher: SimpleTextWatcher? = null
if (listener != null) {
simpleTextWatcher = SimpleTextWatcher(listener, edit.editView)
}
edit.editView.addTextChangedListener(simpleTextWatcher)
}
var flag: Boolean = true
var oldCount: Int = -1
class SimpleTextWatcher : TextWatcher {
lateinit var edit: EditText
lateinit var listener: InverseBindingListener
constructor(listener: InverseBindingListener, edit: EditText) {
this.listener = listener
this.edit = edit
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
edit.setSelection(edit.text.length)
if (oldCount == 0) {
oldCount = count
return
}
if (oldCount != 0) {
flag = true
}
if (!flag) {
return
}
listener.onChange()
}
override fun afterTextChanged(s: Editable?) {
}
}
|