This is my code and this run without error:
mobile.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
StringBuilder digits = new StringBuilder();
StringBuilder phone = new StringBuilder();
char[] chars = mobile.getText().toString().toCharArray();
for (int x = 0; x < chars.length; x++) {
if (Character.isDigit(chars[x])) {
digits.append(chars[x]);
}
}
//Format for 6 digits and below
if (digits.toString().length() >= 6) {
String six = new String();
six += digits.toString();
phone.append(six);
//Format for 7 digits
if (digits.toString().length() >= 7) {
phone.setLength(0);
String countryCode = new String();
countryCode += digits.toString().substring(0, 3) + "-";
countryCode += digits.toString().substring(3,7);
phone.append(countryCode);
//Format for 8 and 9 digits
if (digits.toString().length() >= 8) {
phone.setLength(0);
String eight = new String();
eight += digits.toString();
phone.append(eight);
//Format for 10 digits
if (digits.toString().length() >= 10) {
phone.setLength(0);
String regionCode = new String();
regionCode += "(" + digits.toString().substring(0, 3) + ") ";
regionCode += digits.toString().substring(3, 6) + "-";
phone.append(regionCode);
//Format for 11 digits
if (digits.toString().length() >= 11) {
String code = new String();
phone.setLength(0);
code += digits.toString().substring(0, 1);
code += "(" + digits.toString().substring(1, 4) + ")- ";
code += digits.toString().substring(4, 7) + "-";
code += digits.toString().substring(7, 11);
phone.append(code);
//Format for 12 digits
if (digits.toString().length() >= 12) {
String newCode = new String();
phone.setLength(0);
newCode += "+" + digits.toString().substring(0, 2);
newCode += "(" + digits.toString().substring(2, 5) + ")";
newCode += digits.toString().substring(5, 8) + "-";
newCode += digits.toString().substring(8, 12);
phone.append(newCode);
//Format for 12 digits and more
if (digits.toString().length() >= 13) {
String noMoreThanTwelve = new String();
phone.setLength(0);
noMoreThanTwelve += digits.toString();
phone.append(noMoreThanTwelve);
}
}
} else {
phone.append(digits.toString().substring(6));
}
}
}
}
mobile.removeTextChangedListener(this);
mobile.setText(phone.toString());
mobile.setSelection(mobile.getText().toString().length());
mobile.addTextChangedListener(this);
} else {
return;
}
}
});
This is the output of my code:
Below 7 digits:
123456 = 123456
7 Digits:
1234567 = 123-4567
8 Digits
12345678 = 12345678
9 Digits
123456789 = 123456789
10 Digits
1234567890 = (123) 456-7890
11 Digits
12345678901 = 1 (234) 567-8901
12 Digits
123456789012 = +12 (345) 678-9012
More than 12 Digits
12345678901234 ....
Sorry for using these variables but I do hope you understand my code.