有没有一种方法可以在用户打字时将 EditText 中的字符分组到块中?示例:1234
4567
7890
等等?
我有一个支持数字且长度为 16 个字符的编辑文本,我想将它们分组在单独的块中以获得更好的可见性。
editText.addTextChangedListener(new FourDigitCardFormatWatcher(editText));
每 4 位数字添加一个空格。使用以下代码。
public class FourDigitCardFormatWatcher implements TextWatcher {
// Change this to what you want... ' ', '-' etc..
private final String space = " ";
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", "");
if (processed.length() > 4){
processed = processed.replaceAll("(\\d{4})(?=\\d)", "$1 ");
}
//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);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)