在輸入電話號碼的時候,咱們看到不少app能夠輸入130 xxxx xxxx的格式,即中間空一格。以下圖
其實作起來也比較簡單,只要在輸入的時候實現TextWatcher監聽就好,具體的監聽代碼以下:app
phone.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @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--; } } phone.setText(sb.toString()); phone.setSelection(index); } } @Override public void afterTextChanged(Editable editable) { } });
其中phone即爲輸入電話號碼的編輯框。僅這一處改變,其餘按照正常操做就好。ide