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

13年前
开发过程经常遇到要输入用户名等类似要限制输入字数的要求,我们可以用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);     }
用这样方法的优点是可以用在多个输入框中,可是有个缺点是当用联想输入法一次输入较长的中文词语或英文单词后,不会自动截断词语或单词。