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; }
mEditText.setFilters(new InputFilter[] { new LengthFilter(mMaxTextNum) });
代码很少但有效,各位可以尝试一下。
作者:xzy2046,转载需注明。博客主页:http://blog.csdn.net/xzy2046
时间: 2024-11-08 21:43:28