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 >
import android.os.Handler
import android.text.Editable
import android.text.TextWatcher
class EndTypingWatcher(
var delayMillis: Long = DELAY,
val action: () -> Unit
) : Handler(), TextWatcher {
companion object {
private const val DELAY: Long = 1000
}
var lastEditTime: Long = 0
private val finishCheckerRunnable = Runnable {
if (System.currentTimeMillis() > lastEditTime + delayMillis - 500) {
action.invoke()
}
}
override fun afterTextChanged(s: Editable?) {
afterTextChanged()
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
onTextChanged()
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
private fun afterTextChanged() {
lastEditTime = System.currentTimeMillis()
postDelayed(finishCheckerRunnable, delayMillis)
}
private fun onTextChanged() {
removeCallbacks(finishCheckerRunnable)
}
}
Usage:
private const val DELAY_AFTER_STOP_TYPING = 2000
...
editText.addTextChangedListener(EndTypingWatcher(delayMillis = DELAY_AFTER_STOP_TYPING) {
//Some end action
})