Last active
February 9, 2022 10:48
-
-
Save ziyaddinovchiyev/7aafa5323e2eeab014108d2113594ed5 to your computer and use it in GitHub Desktop.
Text change listener: converts dot to comma as you type
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
/** | |
* [this] text manipulation to be applied to | |
* converts dot to comma in input field | |
* prevents second comma | |
* "editing" is used to prevent code to re-execute on recall of doAfterTextChanged after setText() | |
*/ | |
fun TextInputEditText.dotToComma() { | |
// you should set inputType to numberDecimal from xml | |
keyListener = DigitsKeyListener.getInstance("1234567890.,") | |
var editing = false | |
doAfterTextChanged { editable -> | |
if (!editing) { | |
editing = true | |
editable?.let { text -> | |
if (text.contains('.', false)) { | |
val dotsReplaced = text.toString().replace('.', ',') | |
if (dotsReplaced.count { it == ',' } > 1) { | |
val index = text.lastIndexOf('.') | |
val commaDeleted = text.toString().removeRange(index, index + 1) | |
setText(commaDeleted) | |
setSelection(text.length - 1) | |
} else { | |
setText(dotsReplaced) | |
setSelection(text.length) | |
} | |
return@let | |
} | |
if (text.count { it == ',' } > 1) { | |
val index = text.lastIndexOf(',') | |
val lastCommaDeleted = text.toString().removeRange(index, index + 1) | |
setText(lastCommaDeleted) | |
setSelection(text.length - 1) | |
} | |
} | |
editing = false | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment