項目中需要輸入框自動將輸入內容格式化爲###.###.###-##
就需要對輸入內容格式化後,重新調用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();
}
}