Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting EditText phone number as user types

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());
        }
    }
}
like image 720
Guilherme Avatar asked Oct 02 '22 02:10

Guilherme


1 Answers

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

like image 141
donfuxx Avatar answered Oct 03 '22 15:10

donfuxx