Skip to content

Instantly share code, notes, and snippets.

@afollestad
Created December 14, 2018 19:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afollestad/2a9709b13087a7cd34da140e76c09e96 to your computer and use it in GitHub Desktop.
Save afollestad/2a9709b13087a7cd34da140e76c09e96 to your computer and use it in GitHub Desktop.
import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText
fun EditText.onTextChanged(
@IntRange(from = 0, to = 10000) debounce: Int = 0,
cb: (String) -> Unit
) {
addTextChangedListener(object : TextWatcher {
val callbackRunner = Runnable {
cb(text.trim().toString())
}
override fun afterTextChanged(s: Editable?) = Unit
override fun beforeTextChanged(
s: CharSequence,
start: Int,
count: Int,
after: Int
) = Unit
override fun onTextChanged(
s: CharSequence,
start: Int,
before: Int,
count: Int
) {
removeCallbacks(callbackRunner)
if (debounce == 0) {
callbackRunner.run()
} else {
postDelayed(callbackRunner, debounce.toLong())
}
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment