码迷,mamicode.com
首页 > 其他好文 > 详细

银行卡输入特效 4个加一空格

时间:2016-06-12 20:19:47      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:

private static final char kongge = ‘ ‘;
private TextWatcher textWatcher=new TextWatcher() {

//改变之前text长度
int beforeTextLength = 0;
//改变之前的文字
private CharSequence beforeChar;
//改变之后text长度
int onTextLength = 0;
//是否改变空格或光标
boolean isChanged = 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;

}

@Override
public void afterTextChanged(Editable s) {
if (isChanged) {
location = yourCardNumEd.getSelectionEnd();
int index = 0;
while (index < buffer.length()) {
if (buffer.charAt(index) == kongge) {
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, kongge);
konggeNumberC++;
}
index++;
}
if (konggeNumberC > konggeNumberB) {
location += (konggeNumberC - konggeNumberB);
}

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;
}

yourCardNumEd.setText(str);
Editable etable = yourCardNumEd.getText();
if (location>20){
ToastUtil.ToastShow("最多才能输入20");
return;
}

Selection.setSelection(etable, location);

isChanged = false;
}
}

};

银行卡输入特效 4个加一空格

标签:

原文地址:http://www.cnblogs.com/fajuaryzpf/p/5578583.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!