现实中经常遇到要输入特殊格式的字符串,比如MAC地址,IP地址等,可以自动匹配需要的 格式。实现方式是通过EditText.addTextChangedListener(TextWatcher)
TextWatcher实现方式如下:
- class MyTextWatcher implements TextWatcher{
- private boolean mWasEdited = false;
- @Override
- public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
- @Override
- public void onTextChanged(CharSequence s, int start, int before, int count) {}
- @Override
- public void afterTextChanged(Editable s) {
- if(mWasEdited){
- mWasEdited = false;
- return;
- }
- mWasEdited = true;
- String newString;
- // 根据需求封装字符串
- // 替换字符串
- s.replace(0,s.length(),newString);
- }
- }
附上一段实现MAC格式输入的代码(格式:00-00-00-00-00-00)
- class MacTextWatcher implements TextWatcher{
- private boolean mWasEdited = false;
- @Override
- public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
- @Override
- public void onTextChanged(CharSequence s, int start, int before, int count) {}
- @Override
- public void afterTextChanged(Editable s) {
- if(mWasEdited){
- mWasEdited = false;
- return;
- }
- mWasEdited = true;
- String mac = s.toString();
- mac = mac.toUpperCase().replace("-","").replace(":","");
- StringBuilder builder = new StringBuilder();
- for(int i=0;i<mac.length()&&i<12;i++){
- builder.append(mac.charAt(i));
- if(i%2!=0&&i!=mac.length()-1&&i!=11){
- builder.append("-");
- }
- }
- s.replace(0,s.length(),builder.toString());
- }
- }