EditText电话号码格式化输入、删除案例
我们在输入电话号码的时候,一般都会切割一个较长的电话号码。这种话效果会好非常多。。对EditText的监听能够轻松的实现这个需求。仅仅须要我们给相应的EditText加一个监听就OK了。。贴一下我写的一个watcher
public static class MyTextWatcher implements TextWatcher { private EditText numberEditText; private Button confirmButton; int beforeLen = 0; int afterLen = 0; public MyTextWatcher(EditText numberEditText, Button confirmButton) { this.numberEditText = numberEditText; this.confirmButton = confirmButton; } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { beforeLen = s.length(); } @Override public void afterTextChanged(Editable s) { String txt = numberEditText.getText().toString(); afterLen = txt.length(); if (afterLen > beforeLen) { if (txt.length() == 4 || txt.length() == 9) { numberEditText.setText(new StringBuffer(txt).insert( txt.length() - 1, " ").toString()); numberEditText.setSelection(numberEditText.getText() .length()); } } else { if (txt.startsWith(" ")) { numberEditText.setText(new StringBuffer(txt).delete( afterLen - 1, afterLen).toString()); numberEditText.setSelection(numberEditText.getText() .length()); } } } }
使用的时候仅仅须要new 这个watcher。传入当前的Edittext就可以