之前在网上看到一个大神做了这个,但是有bug,输入几位之后再插入的时候会向后跳一位。所以我进行了修改。大神的网址忘记了,这里就不贴了。
/**
* 银行卡四位加空格
*
* @param mEditText
*/
protected void bankCardNumAddSpace(final EditText mEditText) {
mEditText.addTextChangedListener(new TextWatcher() {
int beforeTextLength = 0;
int onTextLength = 0;
boolean isChanged = false;
boolean isDelete = false;
int location = 0;// 记录光标的位置
private char[] tempChar;
private StringBuffer buffer = new StringBuffer();
int konggeNumberB = 0;
@Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
beforeTextLength = s.length();
if (buffer.length() > 0) {
buffer.delete(0, buffer.length());
}
konggeNumberB = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ' ') {
konggeNumberB++;
}
}
}
@Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
onTextLength = s.length();
buffer.append(s.toString());
if (onTextLength == beforeTextLength || onTextLength <= 3
|| isChanged) {
isChanged = false;
return;
}
isChanged = true;
if(count == 0)
isDelete = true;
else
isDelete = false;
}
@Override
public void afterTextChanged(Editable s) {
if (isChanged) {
location = mEditText.getSelectionEnd();
int index = 0;
while (index < buffer.length()) {
if (buffer.charAt(index) == ' ') {
buffer.deleteCharAt(index);
} else {
index++;
}
}
index = 0;
int konggeNumberC = 0;
while (index < buffer.length()) {
if ((index == 4 || index == 9 || index == 14 || index == 19)) {
buffer.insert(index, ' ');
konggeNumberC++;
}
index++;
}
if(mEditText.getSelectionEnd() != s.toString().length() ){
if ((mEditText.getSelectionEnd() == 5 || mEditText.getSelectionEnd() == 10 || mEditText.getSelectionEnd() == 15 || mEditText.getSelectionEnd() == 20) && !isDelete) {
konggeNumberC++;
}
}
if (konggeNumberC > konggeNumberB) {
location++;
}
if(location < buffer.length()){
if(mEditText.getSelectionEnd() != 5 && mEditText.getSelectionEnd() != 10 && mEditText.getSelectionEnd() != 15 && mEditText.getSelectionEnd() != 20){
if(konggeNumberB == 1 && konggeNumberC == 2){
location--;
}
if(konggeNumberB == 2 && konggeNumberC == 3){
location--;
}
if(konggeNumberB == 3 && konggeNumberC == 4){
location--;
}
}
}
tempChar = new char[buffer.length()];
buffer.getChars(0, buffer.length(), tempChar, 0);
String str = buffer.toString();
if (location > str.length()) {
location = str.length();
} else if (location < 0) {
location = 0;
}
mEditText.setText(str);
Editable etable = mEditText.getText();
Selection.setSelection(etable, location);
isChanged = false;
}
}
});
}