I am trying to format an edit text so when the user types the first two numbers, an '
is automatically added, then, after the two next numbers types a .
so the final result looks like this: 12'34'567
The formatting works correctly, except that when the user deletes a character the '
and .
get eliminated and the textview changes to 123456
. Is there a way in which I can handle formatting of the edit text in a better way? Here is the code of my formatter:
private fun setCoordenatesFormat(editText: EditText){
editText.doOnTextChanged { text, start, count, after ->
if(editText.text.length==2){
editText.setText("${text.toString()}'")
editText.setSelection(3)
}
if(editText.text.length==5){
editText.setText("${editText.text}.")
editText.setSelection(6)
}
}
}
Thanks in advance for all your help
This is not the best approach but you could try and detect when the user is deleting the textview and with the length of the text you can know in which segment you are and avoid the deleting of your desired format. You will have to accomplish this with a TextWatcher.
editText.addTextChangedListener(object: TextWatcher{
override fun afterTextChanged(s: Editable?) {}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
if(after<count){
//got deleted
}
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
//your code on textchanged
}
})