Skip to content

Instantly share code, notes, and snippets.

@rommansabbir
Created October 18, 2021 10:12
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rommansabbir/c56cb28e84bdc499cfd7c63180fb9f95 to your computer and use it in GitHub Desktop.
Save rommansabbir/c56cb28e84bdc499cfd7c63180fb9f95 to your computer and use it in GitHub Desktop.
/**
* Add an action which will be invoked when the text is changing.
*
* @return the [EditText.onTextChangeListener] added to the [EditText]
*/
inline fun EditText.doAfterTextChanged(
delay: Long = 500,
crossinline onTextChangedDelayed: (text: String) -> Unit
) = onTextChangeListener(delay, onTextChangedDelayed)
/**
* Add an action which will be invoked after the text changed.
*
* @return the [EditText.onTextChangeListener] added to the [EditText]
*/
inline fun EditText.onTextChangeListener(
delay: Long,
crossinline onTextChangedDelayed: (text: String) -> Unit
): TextWatcher{
val listener = object : TextWatcher{
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(s: Editable?) {
handlerPostDelayed(delay) { onTextChangedDelayed.invoke(s?.toString() ?: "") }
}
}
this.addTextChangedListener(listener)
return listener
}
var handlerDelayTimer: Timer = Timer()
inline fun handlerPostDelayed(delay: Long, crossinline onSuccess: () -> Unit) {
handlerDelayTimer.cancel()
handlerDelayTimer = Timer()
handlerDelayTimer.schedule(object : TimerTask() {
override fun run() {
Handler(Looper.getMainLooper()).post {
onSuccess.invoke()
}
}
}, delay)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment