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());
}
}
}
You need to be careful with calling setText method inside TextWatcher. Otherwise you create an infinite loop, because you are always changing the text.
You could try the following an only set the text if it is really necessary:
if(!telephone.getText().toString().equals(formatted)) {
telephone.setText(formatted);
}
Instead of just:
telephone.setText(formatted);
That way you should be able to avoid creating an infinite loop
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With