我们在输入电话号码的时候,一般都会分割一个较长的电话号码,这样的话效果会好很多。。对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即可
EditText电话号码格式化输入、删除案例,布布扣,bubuko.com
原文地址:http://blog.csdn.net/yaya_soft/article/details/38383143