开发过程经常遇到要输入用户名等类似要限制输入字数的要求,我们可以用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) {
-
- //返回宽度,目测是像素数Return the width of the text.
- float w = mPaint.measureText(dest.toString() + source.toString());
- if (w > mMaxWidth) {
- 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);
- }
用这样方法的优点是可以用在多个输入框中,可是有个缺点是当用联想输入法一次输入较长的中文词语或英文单词后,不会自动截断词语或单词。
(转载,,未测)