2016-12-27 4 views
0

My FourDigitCardFormatWatcher 4つの数字の後にスペースを1つ追加します。 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 "); 

私のために働いたこの種のを、あなたは変更する必要がありますそれはあなたの要件に合わせて。

それはあなたを助けるはずです、私は願っています!

関連する問題