项目中需要输入框自动将输入内容格式化为###.###.###-##
就需要对输入内容格式化后,重新调用EditText的setText方法设置格式化后的文本,不过处理关于光标的问题有点细节,关于用户在输入内容中间增加或删除字符后,光标就乱了,最开始处理所有的修改都将光标置于尾部,体验不太好,所以好好处理了下,大家看下有没有c、v的可能性吧。
其实就是记录根据发生变化的起始下标和增加的文本长度,根据0到起始下标+增加文本长度格式化重新计算下标 设置下标位置
talk is cheap,show code
etCpf.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
formatCpf(s.toString(), etCpf, start, count);
}
@Override
public void afterTextChanged(Editable s) {
}
});
private static final String CPF_PATTERN = "[0-9]{3}\\.+[0-9]{3}\\.+[0-9]{3}-+[0-9]{2}";
private static String formatCpf(String cpf, EditText editText, int start, int count) {
if (Pattern.matches(CPF_PATTERN, cpf)) {
return cpf;
} else {
String realCpf = cpf.replaceAll("-", "").replaceAll("\\.", "");
StringBuilder sbCpf = new StringBuilder();
if (realCpf.length() > 9) {
sbCpf.append(realCpf, 0, 3)
.append(".")
.append(realCpf, 3, 6)
.append(".")
.append(realCpf, 6, 9)
.append("-")
.append(realCpf.substring(9));
} else if (realCpf.length() > 6) {
sbCpf.append(realCpf, 0, 3)
.append(".")
.append(realCpf, 3, 6)
.append(".")
.append(realCpf.substring(6));
} else if (realCpf.length() > 3) {
sbCpf.append(realCpf, 0, 3)
.append(".")
.append(realCpf.substring(3));
} else {
sbCpf.append(realCpf);
}
if (!TextUtils.equals(cpf, sbCpf.toString())) {
editText.setText(sbCpf);
String selectStr = cpf.substring(0, start + count).replaceAll("-", "").replaceAll("\\.", "");
int selectIndex;
if (selectStr.length() > 9) {
selectIndex = selectStr.length() + 3;
} else if (selectStr.length() > 6) {
selectIndex = selectStr.length() + 2;
} else if (selectStr.length() > 3) {
selectIndex = selectStr.length() + 1;
} else {
selectIndex = selectStr.length();
}
if (selectIndex >= 0) {
editText.setSelection(selectIndex);
}
}
return sbCpf.toString();
}
}