android - Formatting EditText phone number as user types -
i'd edit edittext
field content everytime user types new character. want format phone number using libphonenumber
.
i implemented textwatcher
reads field content , formats phone format. every time set edittext
text formatted string, watcher called again, sets text once more, , gets stuck in infinite loop.
what best or proper way edit text 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 thrown: " + e.tostring()); } } }
you need careful calling settext method inside textwatcher. otherwise create infinite loop, because changing text.
you try following set text if really necessary:
if(!telephone.gettext().tostring().equals(formatted)) { telephone.settext(formatted); }
instead of just:
telephone.settext(formatted);
that way should able avoid creating infinite loop
Comments
Post a Comment