2016-12-27 55 views
0

我的FourDigitCardFormatWatcher在每4個數字後面加一個空格。我想將FourDigitCardFormatWatch更改爲以下格式55555 5555 555 55.格式TextWatcher android

如何確定5位數字後添加空格,然後4位數字後添加空格,3位數後添加空格。

實際結果:4444 4444 4444

預期結果:44444 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 "); 

這種工作對我來說,你可能需要改變它適合您的要求。

這應該對你有所幫助,我希望!