background
Verbose, multi-method callback code affects readability, and the reader’s mood, so much that he or she doesn’t want to maintain it.
Simple, I just need to print in the onTextChanged method. afterTextChanged and beforeTextChanged are redundant
editText.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?).{}override fun beforeTextChanged(s: CharSequence? , start:Int, count: Int, after: Int){}override fun onTextChanged(s: CharSequence? , start:Int, before: Int, count: Int) {
logd(content = "$s.$start.$before.$count"); }})Copy the code
In practice, there may be far more than three method callbacks. There are many other scenarios where these interfaces are mixed together.
To improve the
Simply implement an empty interface
editText.addTextChangedListener(object : TextWatcherEmptyImpl() {
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
logd(content = "$s, $start, $before, $count");
}
})
Copy the code
The dependency implementation is as follows:
// Open class TextWatcherEmptyImpl: TextWatcher {override fun afterTextChanged(s: Editable?) { } override fun beforeTextChanged(s: CharSequence? , start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence? , start: Int, before: Int, count: Int) { } }Copy the code
Kotlin closure implementation
editText.addTextChangedListener {
onTextChanged { s, start, before, after ->
logd(content = "$s,$start,$before,$after") }
}
Copy the code
The dependency implementation is as follows:
/ / support kotlin style extension function to rewrite fun EditText. AddTextChangedListener (init: (TextWatcherKotlinImpl.() -> Unit)) = this.addTextChangedListener( TextWatcherKotlinImpl().apply { init() } ) // Class TextWatcherKotlinImpl(var beforeTextChanged: ((CharSequence? , Int, Int, Int) -> Unit)? = null, var onTextChanged: ((CharSequence? , Int, Int, Int) -> Unit)? = null, var afterTextChanged: ((Editable?) -> Unit)? = null ) : TextWatcher { override fun beforeTextChanged(s: CharSequence? , start: Int, count: Int, after: Int) { beforeTextChanged? .invoke(s, start, count, after) } override fun onTextChanged(s: CharSequence? , start: Int, before: Int, count: Int) { onTextChanged? .invoke(s, start, before, count) } override fun afterTextChanged(s: Editable?) { afterTextChanged? .invoke(s) } fun beforeTextChanged(listener: ((CharSequence? , Int, Int, Int) -> Unit)) { beforeTextChanged = listener } fun onTextChanged(listener: ((CharSequence? , Int, Int, Int) -> Unit)) { onTextChanged = listener } fun afterTextChanged(listener: ((Editable?) -> Unit)) { afterTextChanged = listener } }Copy the code
conclusion
Easy to remember to put a picture to compare the simplicity