具体逻辑实现如下:
editText.addTextChangedListener(new TextWatcher() {
private int oldLength = 0;
private boolean isChange = true;
private int curLength = 0;
private int emptyNumB = 0;
private int emptyNumA = 0;
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
oldLength = s.length();
Log.i(TAG, "未改变长度: " + oldLength);
emptyNumB = 0;
for (int i = 0; i < s.toString().length(); i++) {
if (s.charAt(i)==' ') emptyNumB++;
}
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
curLength = s.length();
Log.i(TAG, "当前长度: " + curLength);
if (curLength == oldLength || curLength <= 3) {
isChange = false;
} else {
isChange = true;
}
}
@Override
public void afterTextChanged(Editable s) {
if (isChange) {
int selectIndex = editText.getSelectionEnd();//获取光标位置
String content = s.toString().replaceAll(" ", "");
Log.i(TAG, "content:" + content);
StringBuffer sb = new StringBuffer(content);
//遍历加空格
int index = 1;
emptyNumA = 0;
for (int i = 0; i < content.length(); i++) {
if ((i + 1) % 4 == 0) {
sb.insert(i + index, " ");
index++;
emptyNumA++;
}
}
Log.i(TAG, "result content:" + sb.toString());
String result = sb.toString();
if (result.endsWith(" ")) {
result = result.substring(0, result.length() - 1);
}
editText.setText(result);
if (emptyNumA > emptyNumB)
selectIndex = selectIndex + (emptyNumA - emptyNumB);
//处理光标位置
if (selectIndex > result.length()||selectIndex+1 == result.length()){
selectIndex = result.length();
}else if (selectIndex < 0){
selectIndex = 0;
}
editText.setSelection(selectIndex);
isChange = false;
}
}
});
如果是有银行卡添加的需求,自动补充空格应该是比较常见的需求,这里分享给大家了,有问题互相交流,谢谢!
傻小孩b
20160219