您的位置:首页 > 移动开发 > Android开发

安卓输入框实现电话号码"344"格式

2016-04-07 00:54 489 查看
效果如图所示:



对edittext添加一个 TextWatcher,对应的 3个方法进行重载:

private class MyTextWatcher implements TextWatcher {
public MyTextWatcher(EditText etPhone) {
this.etPhone = etPhone;
}

private EditText etPhone;
private boolean isAdd;

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if (after == 1) {//增加
isAdd = true;
} else {
isAdd = false;
}
}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {

}

@Override
public void afterTextChanged(Editable s) {
if (isAdd) {
if (null != etPhone) {
String str = s.toString();
if (!str.endsWith(" ")) {
int length = s.length();
if (length == 3 || length == 8) {
String str1 = str + " ";//手动添加空格
etPhone.setText(str1);
etPhone.setSelection(str1.length());//光标移到最右边
}
}
}
}
}
}


beforeTextChanged(CharSequence s, int start, int count, int after)

这个方法是在Text改变之前被调用,它的意思就是说在原有的文本s中,从start开始的count个字符将会被一个新的长度为after的文本替换,注意这里是将被替换,还没有被替换。所以当我们添加一个数字的时候,after是1,也就是说只有在这种情况下 (after== 1) 我们才要对数字进行格式化
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息