I'd like to edit an EditText
field content everytime the user types a new character. Basically I want to format a phone number using libphonenumber
.
I implemented a TextWatcher
that reads the field content and formats it into the phone format. But every time I set the EditText
text with the formatted string, the watcher is called again, sets the text once more, and it gets stuck in this infinite loop.
What is the best or proper way to edit the text as user types?
@Override
public void afterTextChanged(Editable editable) {
if (editable.length() > 1) {
try {
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
PhoneNumber numberProto = phoneUtil.parse(editable.toString(), "BR");
String formatted = phoneUtil.format(numberProto, PhoneNumberFormat.NATIONAL);
telephone.setText(formatted);
} catch (NumberParseException e) {
Log.d("Telefone", "NumberParseException was thrown: " + e.toString());
}
}
}