1. 自定义类PhoneTextView
PhoneTextView
继承EditText
,在构造函数里面可以初始化类型,限定长度和输入类型,并添加TextWatcher
监听器。
public class PhoneTextView extends EditText {
public PhoneTextView(Context context) {
this(context, null);
}
public PhoneTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setFilters(new InputFilter[] {new InputFilter.LengthFilter(13)});
setInputType(InputType.TYPE_CLASS_NUMBER);
new PhoneTextWatcher(this);
}
}
2. 自定义TextWatcher
TextWatcher
主要用于监听EditText
的文本变化,详情可见TextWatcher监听器。
覆盖onTextChanged()
方法,去除空格,并调整光标的位置。
static class PhoneTextWatcher implements TextWatcher {
private static final char SPACE_CHAR = ' ';
private EditText mEditText;
PhoneTextWatcher(EditText editText) {
this.mEditText = 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) {
int selection = start + count;
char[] array = new char[s.length()];
int len = 0;
int space = 0;
for (int index = 0; index < s.length(); index++) {
if (s.charAt(index) == SPACE_CHAR) {
if (index < selection) {
++space;
}
} else {
array[len++] = s.charAt(index);
}
}
setPhoneText(new String(array, 0, len), selection - space);
}
@Override
public void afterTextChanged(Editable s) {
}
}
setPhoneText()
方法,通过isEmptyPlace(int)
方法来判断是否需要添加空格,并调整光标。在设置新的字符时,要先关闭监听器。
private void setPhoneText(String phoneText, int selection) {
LogTool.logi("PhoneTextView", phoneText + ", selection = " + selection);
String text = "";
int space = 0;
for (int index = 0; index < phoneText.length(); index++) {
if (isEmptyPlace(text.length())) {
text += SPACE_CHAR;
if (index < selection) {
++space;
}
}
text += phoneText.charAt(index);
}
mEditText.removeTextChangedListener(this);
mEditText.setText(text);
mEditText.setSelection(selection + space);
mEditText.addTextChangedListener(this);
}
private boolean isEmptyPlace(int index) {
return 3 == index || 8 == index;
}