EditText输入字数限制,超出限定字数Toast提示

自定义实现InputFilter,当达到最大长度后,继续输入字符每次都弹toast实现
代码实现:

public class MaxTextLengthFilterUtils implements InputFilter {
    private int mMaxLength;
    private int mToast;

    public MaxTextLengthFilterUtils(int max, int toast) {
        mMaxLength = max - 1;
        mToast = toast;
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        int keep = mMaxLength - (dest.length() - (dend - dstart));
        if (keep < (end - start)) {
            UIUtils.showToastSafe(mToast);
        }
        if (keep <= 0) {
            return "";
        } else if (keep >= end - start) {
            return null;
        } else {
            return source.subSequence(start, start + keep);
        }
    }

}

调用方法:edittext.setFilters(new InputFilter[]{new MaxTextLengthFilterUtils(20, “这里是提示语”)});
忘了从哪个小伙伴那里看到的了,现在整理代码,记录一下,望见谅。

你可能感兴趣的:(android)