266
CHAPTER 10: Development
What you could do, however, is extend the EditText class in
a utility file and add the
possibility to provide a simplified text changed listener. To do so, start with such a file, for
example, utility.kt inside package com.example or of course any package of your app.
Add the following:
fun EditText.addTextChangedListener(l:
(CharSequence?, Int, Int, Int) -> Unit) {
this.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) {
l(s, start, before, count)
}
})
}
This adds the desired method to that class dynamically.
You can now use import com.example.utility.* anywhere
needed and then write the
following, which looks considerably more concise compared to the original construct:
val et = ... // the EditText view
et.addTextChangedListener({ s: CharSequence?,
start: Int, before: Int, count: Int ->
// do s.th.
})
Multithreading
We already talked about multithreading to some extent in Chapter 9. In this section, we just
point out what Kotlin on a language level can do to simplify multithreading.
Kotlin contains a couple of utility functions inside its standard library.
They help to start
threads and timers more easily compared to using the Java API; see Table
10-1
.