android 格式化输入控制

来源:互联网 发布:js中转换日期格式 编辑:程序博客网 时间:2024/05/29 02:15

Article from : http://horribile.blogspot.com/2011/11/formatting-edittext-input-with-regular.html

It will be the short article. Now we will format text in EditText with regular expressions.


The simple class will extend Input Filter:

view plainprint?
  1. public class PartialRegexInputFilter implements InputFilter {  
  2.    
  3.     private Pattern mPattern;  
  4.    
  5.     public PartialRegexInputFilter(String pattern){  
  6.       mPattern = Pattern.compile(pattern);  
  7.     }   
  8.   
  9.     @Override  
  10.     public CharSequence filter(CharSequence source,  
  11.             int sourceStart, int sourceEnd,  
  12.             Spanned destination, int destinationStart,  
  13.             int destinationEnd)   
  14.     {    
  15.         String textToCheck = destination.subSequence(0, destinationStart).  
  16.             toString() + source.subSequence(sourceStart, sourceEnd) +  
  17.             destination.subSequence(  
  18.             destinationEnd, destination.length()).toString();  
  19.     
  20.         Matcher matcher = mPattern.matcher(textToCheck);  
  21.     
  22.         // Entered text does not match the pattern  
  23.         if(!matcher.matches()){  
  24.      
  25.             // It does not match partially too  
  26.              if(!matcher.hitEnd()){  
  27.                  return "";  
  28.              }  
  29.      
  30.         }  
  31.     
  32.         return null;  
  33.     }  
  34.   
  35. }  

The trick is that if the input text does not match the pattern it can match it partially.
If so we will allow the text pasting.

And finally formatting a phone number:

view plainprint?
  1. final String regex = "\\(\\d{3}\\)\\d{3}\\-\\d{2}\\-\\d{2}";  
  2.           
  3. txt.setFilters(  
  4.     new InputFilter[] {  
  5.         new PartialRegexInputFilter(regex)  
  6.     }  
  7. );  
  8.           
  9. txt.addTextChangedListener(  
  10.     new TextWatcher(){  
  11.   
  12.             @Override  
  13.             public void afterTextChanged(Editable s) {  
  14.                 String value  = s.toString();  
  15.                 if(value.matches(regex))  
  16.                     txt.setTextColor(Color.BLACK);  
  17.                 else  
  18.                     txt.setTextColor(Color.RED);  
  19.             }  
  20.   
  21.             @Override  
  22.             public void beforeTextChanged(CharSequence s, int start,  
  23.                 int count, int after) {}  
  24.   
  25.             @Override  
  26.             public void onTextChanged(CharSequence s, int start,  
  27.                int before, int count) {}  
  28.              
  29.          }  
  30. );  
  31.           


We have: 

0 0