I have an EditText field in my layout. I want to perform an action when the user stops typing in that edittext field. I have implemented TextWatcher and use its functions
If you use Kotlin, use this extension function:
fun TextView.afterTextChangedDelayed(afterTextChanged: (String) -> Unit) {
this.addTextChangedListener(object : TextWatcher {
var timer: CountDownTimer? = null
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {}
override fun afterTextChanged(editable: Editable?) {
timer?.cancel()
timer = object : CountDownTimer(1000, 1500) {
override fun onTick(millisUntilFinished: Long) {}
override fun onFinish() {
afterTextChanged.invoke(editable.toString())
}
}.start()
}
})
}
Use example:
editTextPassword.afterTextChangedDelayed {
registerViewModel.addUserPassword(it)
}