I need to format a phone number in an edit text in android as per this format (222) 222-2222 ext222222
I have created a watcher that does the auto formatting for me. The watcher works fine and formats the phone number correctly. My only issue is when somebody manually goes to some other position within the entered phone and starts deleting or adding numbers then the auto formatting does not work.
Any ideas how to go about with this issue.
Here is how my current watcher looks like:
editText.addTextChangedListener(object : TextWatcher {
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun afterTextChanged(s: Editable) {
val text = editText.text.toString()
val textLength = editText.text.length
if (text.endsWith("-") || text.endsWith(" ")) {
return
}
if (textLength == 1) {
if (!text.contains("(")) {
editText.setText(StringBuilder(text).insert(text.length - 1, "(").toString())
editText.setSelection(editText.text.length)
}
} else if (textLength == 5) {
if (!text.contains(")")) {
editText.setText(StringBuilder(text).insert(text.length - 1, ")").toString())
editText.setSelection(editText.text.length)
}
} else if (textLength == 6) {
editText.setText(StringBuilder(text).insert(text.length - 1, " ").toString())
editText.setSelection(editText.text.length)
} else if (textLength == 10) {
if (!text.contains("-")) {
editText.setText(StringBuilder(text).insert(text.length - 1, "-").toString())
editText.setSelection(editText.text.length)
}
} else if (textLength == 15) {
if (text.contains("-")) {
editText.setText(StringBuilder(text).insert(text.length - 1, " ext").toString())
editText.setSelection(editText.text.length)
}
}
}
})