2016-12-27 2 views
0

FourDigitCardFormatWatcher 4 자리 숫자마다 공백을 추가하십시오. FourDigitCardFormatWatch을 다음 형식으로 변경하고 싶습니다. 55555 5555 555 55형식 TextWatcher android

5 자리가 공백을 추가 한 다음 4 자리 뒤에 공백을 추가하고 3 자리 뒤에 공백을 추가 한 후 어떻게 결정할 수 있습니까?

실제 결과 : 4444 4444 4444

예상 결과 : 44,444 4444 444

+0

은 아마 당신은 ('^ ... $'정규식을 사용하여)보다는 하위 문자열을 다루는 전체 텍스트를 처리해야 . –

+0

그리고 지금까지 무엇을 시도 했습니까? 분명히 당신은 단지'replaceAll'을 바꾸면됩니다. – Fallenhero

답변

0

편집이 같은 클래스 ..

public class FourDigitCardFormatWatcher implements TextWatcher { 

// Change this to what you want... ' ', '-' etc.. 
private final String char = " "; 
EditText et_filed; 


public FourDigitCardFormatWatcher(EditText et_filed){ 
    this.et_filed = et_filed; 
} 

@Override 
public void onTextChanged(CharSequence s, int start, int before, int count) { 
} 

@Override 
public void beforeTextChanged(CharSequence s, int start, int count, int after) { 
} 

@Override 
public void afterTextChanged(Editable s) { 
    String initial = s.toString(); 
    // remove all non-digits characters 
    String processed = initial.replaceAll("\\D", ""); 

    // insert a space after all groups of 4 digits that are followed by another digit 
    processed = processed.replaceAll("(\\d{5})(\\d{4})(\\d{3})(?=\\d)(?=\\d)(?=\\d)", "$1 $2 $3 "); 

    //Remove the listener 
    et_filed.removeTextChangedListener(this); 

    //Assign processed text 
    et_filed.setText(processed); 

    try { 
     et_filed.setSelection(processed.length()); 
    } catch (Exception e) { 
     // TODO: handle exception 
    } 

    //Give back the listener 
    et_filed.addTextChangedListener(this); 
} 
} 

추가 청취자

editText1.addTextChangedListener(new FourDigitCardFormatWatcher(editText1)); 
0
아래처럼 replaceAll 문을 변경

:

processed = processed.replaceAll("(\\d{5})(\\d{4})(\\d{3})(?=\\d)*", "$1 $2 $3 "); 

나를 위해 일한 이런 종류의, 당신은 변경해야 할 수 있습니다 그것은 귀하의 요구 사항에 맞게.

도움이 될 것입니다.