Android中限制EditText(輸入框)文字輸入長度

開發過程經常遇到要輸入用戶名等類似要限制輸入字數的要求,我們可以用InputFilter來實現,
下面是繼承的InputFilter:
 
 
public class MyInputFilter implements InputFilter { 
 
   private Paint mPaint; 
    
   private int mMaxWidth; 
 
   private static final String TAG = "MyInputFilter"; 
    
   private int EDIT_WIDTH = 280; 
    
   private int mPadding = 10; 
    
   public MyInputFilter(Paint paint, int maxWidth) { 
      if (paint != null) { 
         mPaint = paint; 
      } else { 
         mPaint = new Paint(); 
         mPaint.setTextSize(30F); 
      } 
 
      if (maxWidth > 0) { 
         mMaxWidth = maxWidth – mPadding; 
      } else { 
         mMaxWidth = EDIT_WIDTH; 
      } 
 
   } 
 
 
   @Override 
   public CharSequence filter(CharSequence source, int start, int end, 
         Spanned dest, int dstart, int dend) { 
 
      float w = mPaint.measureText(dest.toString() + source.toString()); 
      if (w > mMaxWidth) { 
         //TODO: remind the user not to input anymore 
         return ""; 
      } 
 
      return source; 
   } 
 

 
這樣來使用它:
 
/*
   * Set edit text input max length constraint to border.
   */ 
  public static void setEditTextFilter(EditText edit) { 
     
     int width = edit.getWidth(); 
     
     Utils.log("Uitls", "edit width = " + width); 
         
     Paint paint = new Paint(); 
     paint.setTextSize(edit.getTextSize()); 
     
     InputFilter[] filters = { new MyInputFilter(paint, width) }; 
     
     edit.setFilters(filters); 
  } 
 
用這樣方法的優點是可以用在多個輸入框中,可是有個缺點是當用聯想輸入法一次輸入較長的中文詞語或英文單詞後,不會自動截斷詞語或單詞。
 
(全文完)

作者 herbert5069的專欄

發佈留言