2014-04-08 2 views
5

사용자가 새 문자를 입력 할 때마다 EditText 필드 내용을 편집하고 싶습니다. 기본적으로 libphonenumber을 사용하여 전화 번호를 형식화하려고합니다.사용자 유형으로 EditText 전화 번호 형식 지정

필자는 TextWatcher을 구현하여 필드 내용을 읽고이를 전화 형식으로 포맷합니다. 그러나 형식화 된 문자열로 EditText 텍스트를 설정할 때마다 watcher가 다시 호출되고 텍스트가 한 번 더 설정되며이 무한 루프에 걸리게됩니다.

사용자 유형으로 텍스트를 편집하는 가장 좋은 방법은 무엇입니까?

@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