Skip to content

Instantly share code, notes, and snippets.

@dakatso
Last active December 25, 2018 11:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dakatso/36706d1dfb74c6210c66d8d699155545 to your computer and use it in GitHub Desktop.
Save dakatso/36706d1dfb74c6210c66d8d699155545 to your computer and use it in GitHub Desktop.
Wrapper for TextWatcher
open class TextWatcherListener(
private val editText: EditText,
private val listener: EditText.(String, String, String, String) -> Unit
) : TextWatcher {
private var before: String = ""
private var old: String = ""
private var new: String = ""
private var after: String = ""
private var isIgnore = false
override fun beforeTextChanged(sequence: CharSequence, start: Int, count: Int, after: Int) {
this.before = sequence.subSequence(0, start).toString()
this.old = sequence.subSequence(start, start + count).toString()
this.after = sequence.subSequence(start + count, sequence.length).toString()
}
override fun onTextChanged(sequence: CharSequence, start: Int, before: Int, count: Int) {
this.new = sequence.subSequence(start, start + count).toString()
}
override fun afterTextChanged(sequence: Editable) {
if (isIgnore) {
return
}
isIgnore = true
listener(editText, before, old, new, after)
isIgnore = false
}
companion object {
fun EditText.addTextChangedListener(listener: EditText.(String, String, String, String) -> Unit) {
addTextChangedListener(TextWatcherListener(this, listener))
}
}
}
editText.addTextChangedListener { before, old, new, after ->
//this <- given EditText
//safe update EditText
val oldString = before + old + after
val newString = before + new + after
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment