Last active
December 25, 2018 11:39
-
-
Save dakatso/36706d1dfb74c6210c66d8d699155545 to your computer and use it in GitHub Desktop.
Wrapper for TextWatcher
This file contains 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
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)) | |
} | |
} | |
} |
This file contains 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
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