2014-04-08 21 views
5

我想每次编辑EditText领域内容的用户的类型的新角色。基本上我想用libphonenumber格式化一个电话号码。格式的EditText电话号码作为用户类型

我实现了一个TextWatcher读取字段内容和格式它插入手机格式。但每次我使用格式化的字符串设置EditText文本时,观察者会再次被调用,再次设置文本,并且会陷入这个无限循环。

什么是编辑文本用户类型,最好还是适当的方法是什么?

@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()); 
     } 
    } 
} 

回答

4

您需要小心调用TextWatcher中的setText方法。否则,你会创建一个无限循环,因为你总是在改变文本。

你可以尝试以下的只设置文本,如果它是真的有必要

if(!telephone.getText().toString().equals(formatted)) { 
    telephone.setText(formatted); 
} 

而不只是:

telephone.setText(formatted); 

这样,你应该能够避免创建无限循环

+0

如果我可以问一个问题,当我改变了文本,光标返回到文本字段的开头。我怎样才能让它停留在最后? – Guilherme

+2

试试这个关于游标定位的答案:http://stackoverflow.com/a/8035171/2399024 – donfuxx