1. 程式人生 > >EditText 限制輸入為中文,個數為6個

EditText 限制輸入為中文,個數為6個

et_real_name.setFilters(new InputFilter[]{new InputChineseFilter(6)});


class InputChineseFilter implements InputFilter {

        private final int mMax;

        public InputChineseFilter(int max) {
            mMax = max;
        }

        /**
         *
         * @param source 新輸入的字串
         * @param start 新輸入的字串起始下標,一般為0
         * @param end 新輸入的字串終點下標,一般為source長度-1
         * @param dest 輸入之前文字框內容
         * @param dstart 原內容起始座標,一般為0
         * @param dend 原內容終點座標,一般為dest長度-1
         * @return
         */
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

            int newSize = source.length();
            if(!StringUtil.checkNameChese(source.toString())){
                ToastUtil.show("姓名必須為中文");
                return "";
            }

            int destSize = dest.length();

            if(destSize >= mMax){
                return "";
            } else if(newSize + destSize > mMax){
                return source.subSequence(0, mMax - destSize);
            } else {
                return null;//為source源資料
            }
        }
    }


工具類

/**
     * 檢測String是否全是中文
     *
     * @param name
     */
    public static boolean checkNameChese(String name) {
        boolean res = true;
        char[] cTemp = name.toCharArray();

        for (int i = 0; i < name.length(); i++) {
            if (!isChinese(cTemp[i])) {
                res = false;
                break;
            }
        }
        return res;
    }


    /* 判定輸入的是否是漢字
     *
     * @param c 被校驗的字元
     * @return true代表是漢字
     */
    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;
    }