在Android開發過程中,有些應用會要求用戶輸入手機號,比如手機號碼驗證,爲了便於觀看,我們都會以188 xxxx xxxx這種格式進行展示。下面就帶領大家實現這種功能。廢話不多說,先上圖:
要實現這種功能,我們的思路是給EditText加一個編輯框監聽器。
核心代碼:
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s == null || s.length() == 0)
return;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (i != 3 && i != 8 && s.charAt(i) == ' ') {
continue;
} else {
sb.append(s.charAt(i));
if ((sb.length() == 4 || sb.length() == 9)
&& sb.charAt(sb.length() - 1) != ' ') {
sb.insert(sb.length() - 1, ' ');
}
}
}
if (!sb.toString().equals(s.toString())) {
int index = start + 1;
if (sb.charAt(start) == ' ') {
if (before == 0) {
index++;
} else {
index--;
}
} else {
if (before == 1) {
index--;
}
}
_text.setText(sb.toString());
_text.setSelection(index);
}
}
onTextChanged()是TextWatcher接口的一個方法,那麼如何使用TextWatcher呢?很簡單,給EditText添加一個addTextChangedListener監聽即可,參數就是一個TextWatcher的實現類。
上面一段代碼並不複雜,就不過多解釋了。當長度爲3或8時我們會添加一個" ",當碰到空格時會默認調整光標的位置。
DEMO下載!!!