StringBuffer phoneNumSpace = new StringBuffer();
et_account.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) {
showError("");
phoneNumSpace.setLength(0);
phoneNumSpace.append(s);
int length = phoneNumSpace.length();//toString().length();
//删除数字
if (count == 0) {
if (length == 4) {
setContent(phoneNumSpace.deleteCharAt(3));
}
if (length == 9) {
setContent(phoneNumSpace.deleteCharAt(8));
}
}
//添加数字
if (count >= 1) {
if (length >= 4)
{
// char[] chars = s.toString().toCharArray();
//数字下标是从0开始
if (phoneNumSpace.charAt(3) != ' ')
{
phoneNumSpace.insert(3,' ');
setContent(phoneNumSpace);
}
}
if (length >= 9)
{
// char[] chars = s.toString().toCharArray();
//因为第4位加了一个空格,所以第8位数字,就是字符数组的第9位,下标是8。
if (phoneNumSpace.charAt(8) != ' ')
{
phoneNumSpace.insert(8,' ');
setContent(phoneNumSpace);
}
}
// if (length == 4) {
// String part1 = s.subSequence(0, 3).toString();
// String part2 = s.subSequence(3, length).toString();
// et_account.setText(part1 + " " + part2);
// }
// if (length==9){
//
// String part1 = s.subSequence(0, 8).toString();
// String part2 = s.subSequence(8, length).toString();
//
// et_account.setText(part1 + " " + part2);
// }
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
private void setContent(StringBuffer sb){
et_account.setText(sb.toString());
//移动光标到最后面
et_account.setSelection(sb.length());
}
|