记Android EditText如何限制汉字输入

通过EditText#setFilters设置InputFilter数组,自定义InputFilter限制只输入汉字,LengthFilter限制输入的字符长度。

public class InputFilterUtils {
    /**
     * 判定输入汉字
     *
     * @param c
     * @return
     */
    public static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }

    public static boolean isNum(char c) {
        if (c < '0' || c > '9') return false;
        return true;
    }

    /**
     * 创建汉字过滤器
     *
     * @return
     */
    public static InputFilter createChineseInputFilter() {
        return new InputFilter() {
            public CharSequence filter(CharSequence source, int start, int end,
                                       Spanned dest, int dstart, int dend) {
                for (int i = start; i < end; i++) {
                    if (!isChinese(source.charAt(i))) {
                        return "";
                    }
                }
                return null;
            }
        };
    }


    /**
     * 创建非数字过滤器
     *
     * @return
     */
    public static InputFilter createNonNumberInputFilter() {
        return new InputFilter() {
            public CharSequence filter(CharSequence source, int start, int end,
                                       Spanned dest, int dstart, int dend) {
                for (int i = start; i < end; i++) {
                    if (isNum(source.charAt(i))) {
                        return "";
                    }
                }
                return null;
            }
        };
    }

}

使用:

    /**
     * 设置自定义输入器,inputMaxLength是EditText的最大字符数
     */
    public void setCustomInputFilter() {
        if (inputMaxLength != -1)
            mEditContent.setFilters(new InputFilter[]{InputFilterUtils.createNonNumberInputFilter(), new InputFilter.LengthFilter(inputMaxLength)});
        else
            mEditContent.setFilters(new InputFilter[]{InputFilterUtils.createNonNumberInputFilter()});
    }

你可能感兴趣的:(记Android EditText如何限制汉字输入)