Android 自定义手机输入框

来源:互联网 发布:淘宝客导购网站有哪些 编辑:程序博客网 时间:2024/04/27 11:32

Android自定义手机输入框

1、自定义类PhoneTextView

继承EditText,在构造函数里面可以初始化类型,限定长度和输入类型,并添加TextWatcher监听器。
setFilters(new InputFilter[] {new InputFilter.LengthFilter(13)});setInputType(InputType.TYPE_CLASS_NUMBER);addTextChangedListener(CustomTextWatcher);

2、TextWatcher监听器

在TextWatcher的onTextChanged(CharSequence s, int start, int before, int count)的方法里面一个有4个参数。
s表示输入框中字符。
start表示光标的位置。如果count大于0,start是光标开始的位置,结束时为start加上count。否则start是光标结束的位置。
before表示原有字符被删除的数量。用delete删除时为1,而在添加字符时为0。
count表示输入字符的长度。添加时为1,删除时为0。
当进行拷贝、剪切、粘贴时,before和count为实际字符的长度。

3、自定义TextWatcher

覆盖onTextChanged方法,去除空格,并调整光标的位置。
@Overridepublic void onTextChanged(CharSequence s, int start, int before, int count) {String newString = "";int empty_num = 0;char[] charArray = s.toString().toCharArray();for (int index = 0; index < charArray.length; index++) {char c = charArray[index];if (c == EMPTY_CHAR) {if (index < start + count) {empty_num++;}} else {newString += c;}}if (count > 0) {setPhoneText(newString, start + count - empty_num);} else {setPhoneText(newString, start - empty_num);}}

4、setPhoneText方法

通过isEmptyPlace方法来判断是否需要添加空格,并调整光标。在设置新的字符时,要先关闭监听器。
private void setPhoneText(String s, int start) {String newStr = "";char[] charArray = s.toString().toCharArray();int empty_num = 0;for (int index = 0; index < charArray.length; index++) {if (isEmptyPlace(index)) {newStr += EMPTY_CHAR;if (index < start) {empty_num++;}}newStr += charArray[index];}removeTextChangedListener(CustomTextWatcher);setText(newStr);start += empty_num;setSelection(start > 0 ? start : 0);addTextChangedListener(CustomTextWatcher);}

0 0