Maximum value input in Android EditText
Sometimes, we add the maximum length limit to EditText. When EditText reaches the input limit, it is blocked from entering the text and a prompt is displayed.
This problem seems simple, but it is difficult to handle perfectly.
Because EditText cannot intercept software disk events, problems may occur in general methods such as TextWatcher and OnKeyListener. After reverse review and error, we finally found the following solutions:
1. Implement an InputFilter, judge the input length in InputFilter, and a prompt is displayed:
public class LengthFilter implements InputFilter { public LengthFilter(int max) { mMax = max; } @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { int keep = mMax - (dest.length() - (dend - dstart)); if (keep <= 0) { if (mErrorToast == null) { mErrorToast = Toast.makeText(ShowDetailCommentActivity.this, R.string.comment_input_overflow, Toast.LENGTH_SHORT); } mErrorToast.show(); return ""; } else if (keep >= end - start) { return null; // keep original } else { keep += start; if (mErrorToast == null) { mErrorToast = Toast.makeText(ShowDetailCommentActivity.this, R.string.comment_input_overflow, Toast.LENGTH_SHORT); } mErrorToast.show(); if (Character.isHighSurrogate(source.charAt(keep - 1))) { --keep; if (keep == start) { return ""; } } return source.subSequence(start, keep); } } private int mMax; }
2. Set this InputFilter to the corresponding EditText:
mEditText.setFilters(new InputFilter[] { new LengthFilter(mMaxTextNum) });
The code is small but valid. You can try it.
Author: xzy2046, which must be noted for reprinting. Blog homepage: http://blog.csdn.net/xzy2046