我的 FourDigitCardFormatWatcher
每4个数字添加一个空间。我想将FourDigitCardFormatWatch
更改为以下格式55555 5555 555 55。
在5个数字添加一个空间之后,我该如何确定,然后在4位数字添加一个空间后,3位数字添加一个空间。
实际结果:4444 4444 4444
预期结果:44444 4444 444
这样编辑类。
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));
更改您的replaceAll
语句如下:
processed = processed.replaceAll("(\d{5})(\d{4})(\d{3})(?=\d)*", "$1 $2 $3 ");
这种对我有用的工作,您可能需要更改它以适合您的要求。
应该帮助您,我希望