Android中限制EditText(输入框)文字输入长度


开发过程经常遇到要输入用户名等类似要限制输入字数的要求,我们可以用InputFilter来实现,

下面是继承的InputFilter:

[java]

  1. public class MyInputFilter implements InputFilter {  
  2.   
  3.    private Paint mPaint;  
  4.      
  5.    private int mMaxWidth;  
  6.   
  7.    private static final String TAG = "MyInputFilter";  
  8.      
  9.    private int EDIT_WIDTH = 280;  
  10.      
  11.    private int mPadding = 10;  
  12.      
  13.    public MyInputFilter(Paint paint, int maxWidth) {  
  14.       if (paint != null) {  
  15.          mPaint = paint;  
  16.       } else {  
  17.          mPaint = new Paint();  
  18.          mPaint.setTextSize(30F);  
  19.       }  
  20.   
  21.       if (maxWidth > 0) {  
  22.          mMaxWidth = maxWidth - mPadding;  
  23.       } else {  
  24.          mMaxWidth = EDIT_WIDTH;  
  25.       }  
  26.   
  27.    }  
  28.   
  29.   
  30.    @Override  
  31.    public CharSequence filter(CharSequence source, int start, int end,  
  32.          Spanned dest, int dstart, int dend) {  
  33.   
  34.       float w = mPaint.measureText(dest.toString() + source.toString());  
  35.       if (w > mMaxWidth) {  
  36.          //TODO: remind the user not to input anymore   
  37.          return "";  
  38.       }  
  39.   
  40.       return source;  
  41.    }  
  42.   
  43. }  

这样来使用它:

[java]
  1. /* 
  2.    * Set edit text input max length constraint to border. 
  3.    */  
  4.   public static void setEditTextFilter(EditText edit) {  
  5.       
  6.      int width = edit.getWidth();  
  7.       
  8.      Utils.log("Uitls""edit width = " + width);  
  9.           
  10.      Paint paint = new Paint();  
  11.      paint.setTextSize(edit.getTextSize());  
  12.       
  13.      InputFilter[] filters = { new MyInputFilter(paint, width) };  
  14.       
  15.      edit.setFilters(filters);  
  16.   }  

用这样方法的优点是可以用在多个输入框中,可是有个缺点是当用联想输入法一次输入较长的中文词语或英文单词后,不会自动截断词语或单词。

(全文完)

相关内容