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;
}