我的FourDigitCardFormatWatcher
在每4个数字后面加一个空格。我想将FourDigitCardFormatWatch
更改为以下格式55555 5555 555 55.格式TextWatcher android
如何确定5位数字后添加空格,然后4位数字后添加空格,3位数后添加空格。
实际结果:4444 4444 4444
预期结果:44444 4444 444
我的FourDigitCardFormatWatcher
在每4个数字后面加一个空格。我想将FourDigitCardFormatWatch
更改为以下格式55555 5555 555 55.格式TextWatcher android
如何确定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 ");
这种工作对我来说,你可能需要改变它适合您的要求。
这应该对你有所帮助,我希望!
也许你应该处理整个文本(使用正则表达式'^ ... $')而不是处理子。 –
到目前为止,你有什么尝试?显然你只需要改变你的'replaceAll' – Fallenhero