Skip to content

Instantly share code, notes, and snippets.

@ziyaddinovchiyev
Last active February 9, 2022 10:48
Show Gist options
  • Save ziyaddinovchiyev/7aafa5323e2eeab014108d2113594ed5 to your computer and use it in GitHub Desktop.
Save ziyaddinovchiyev/7aafa5323e2eeab014108d2113594ed5 to your computer and use it in GitHub Desktop.
Text change listener: converts dot to comma as you type
/**
* [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