Formating while typing.
juanscigliano opened this issue · 1 comments
juanscigliano commented
Formatting while typing makes it losing the format. How can I keep the format while typing?
final PhoneNumberUtil util = PhoneNumberUtil.createInstance(getApplicationContext());
final EditText phone = findViewById(R.id.phone);
phone.addTextChangedListener(new TextWatcher() {
@Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable editable) {
if (editable.length() > 1) {
try {
Phonenumber.PhoneNumber numberProto = util.parse(editable.toString(), "US");
String formatted = util.format(numberProto, PhoneNumberUtil.PhoneNumberFormat.NATIONAL);
if(!phone.getText().toString().equals(formatted)) {
phone.setText(formatted);
phone.setSelection(formatted.length());
}
} catch (NumberParseException e) {
Log.d("Telefone", "NumberParseException was thrown: " + e.toString());
}
}
}
});
MichaelRocks commented
You'd better use AsYouTypeFormatter
. Please take a look at CallMeMaybe project that does exactly what you want.