吴小龙同學

EditText输入手机号自动带空格

转载:http://www.jcodecraeer.com/plus/view.php?aid=3163

在android开发过程中,经常会要求用户输入手机号,为了便于观看,我们都会已135 xxxx xxxx这种格式展示。

1
2
3
4
5
6
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLength="13"
android:inputType="numberSigned" />
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
final EditText editText = (EditText) findViewById(R.id.editText);
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
if (charSequence == null || charSequence.length() == 0)
return;
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < charSequence.length(); i++) {
if (i != 3 && i != 8 && charSequence.charAt(i) == ' ') {
continue;
} else {
stringBuilder.append(charSequence.charAt(i));
if ((stringBuilder.length() == 4 || stringBuilder.length() == 9)
&& stringBuilder.charAt(stringBuilder.length() - 1) != ' ') {
stringBuilder.insert(stringBuilder.length() - 1, ' ');
}
}
}
if (!stringBuilder.toString().equals(charSequence.toString())) {
int index = start + 1;
if (stringBuilder.charAt(start) == ' ') {
if (before == 0) {
index++;
} else {
index--;
}
} else {
if (before == 1) {
index--;
}
}
editText.setText(stringBuilder.toString());
editText.setSelection(index);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
}

联系我:吴小龙同学