I have an EditText
and I want to format the whatever numbers are entered in the EditText
into the US phone number format such as 1(123)123-123 so if the user enters the digit 1 automatically ( will be added this should work for deleting as well. I was able to add a text watcher and set up the logic but I am getting messed up during handling the deletion case.
Here is my code logic to format the first bracket but if we delete the bracket then it wont work
editText.addTextChangedListener(new TextWatcher() {
public int after;
public int before;
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
before = count;
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
after = count;
}
@Override
public void afterTextChanged(Editable s) {
editText.removeTextChangedListener(this);
if (before < after) {
if (s.length() == 4 && s.charAt(0) == '1') {
String formated = "1 (" + s.toString().substring(1, 4) + ")";
editText.setText(formated);
editText.setSelection(editText.getText().toString().length());
}
}
editText.addTextChangedListener(this);
}
});