2014-04-08 17 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