public class NewPhoneTextWatcher implements TextWatcher {
private EditText editText;
private boolean isDelete;
private int lastContentLength;
public NewPhoneTextWatcher(EditText editText)
{
this.editText = editText;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
if (s == null || s.length() == 0) return;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (i != 3 && i != 8&& s.charAt(i) == ' ') {
continue;
} else {
sb.append(s.charAt(i));
if ((sb.length() == 4 || sb.length() == 9) && sb.charAt(sb.length() - 1) != ' ') {
sb.insert(sb.length() - 1, ' ');
}
}
}
if (!sb.toString().equals(s.toString())) {
int index = start + 1;
if (sb.charAt(start) == ' ') {
if (before == 0) {
index++;
} else {
index--;
}
} else {
if (before == 1) {
index--;
}
}
editText.setText(sb.toString());
editText.setSelection(index);
}
}
@Override
public void afterTextChanged(Editable s)
{
//将光标移动到末尾
// editText.setSelection(editText.getText().toString().length());
//处理s
/* //需求是130 1234 4567,中间第4个数字和第5个数字空格前面加空格
StringBuffer sb = new StringBuffer(s);
//StringBuffer.length()是长度,所以下标从1开始
//字符数组第4位如果不是空格字符,就在他前面插一个空格字符
if (s.length() >= 4)
{
String ss = s.toString().replaceAll(" ","");
char[] chars = ss.toString().toCharArray();
//数字下标是从0开始
if (chars[3] != ' ')
{
sb.insert(3,' ');
setContent(sb);
}
}
if (s.length() >= 9)
{
char[] chars = s.toString().toCharArray();
//因为第4位加了一个空格,所以第8位数字,就是字符数组的第9位,下标是8。
if (chars[8] != ' ')
{
sb.insert(8,' ');
setContent(sb);
}
}*/
}
/**
* 添加或删除空格EditText的设置
*/
private void setContent(StringBuffer sb)
{
editText.setText(sb.toString());
//移动光标到最后面
editText.setSelection(sb.length());
}
}
网友评论