Created
December 14, 2018 19:17
-
-
Save afollestad/2a9709b13087a7cd34da140e76c09e96 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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