如何在edittext中避免像�这样的字符?

时间:2017-11-28 13:52:15

标签: android android-edittext

当用户尝试输入复制的文本时,我遇到一个问题,该文本有时包含一些特殊字符,如�

这使得JSON字符串不格式化,所以请问如何避免用户输入这样的字符

请考虑用户只能输入阿拉伯文和英文文本

1 个答案:

答案 0 :(得分:3)

尝试在Edittext上使用InputFilters:

InputFilter filter = new InputFilter() {
        @Override
        public CharSequence filter(CharSequence source, int start, int end,
                                   Spanned dest, int dstart, int dend) {
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = start; i < end; i++) {
                if (isEnglishOrArabicChar(source.charAt(i))) {
                    stringBuilder.append(source.charAt(i));
                }
            }
            return stringBuilder.toString();
        }
    };
etName.setFilters(new InputFilter[]{filter});

private static boolean isEnglishOrArabicChar(char c) {
    Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
    return ub == Character.UnicodeBlock.ARABIC || ub==Character.UnicodeBlock.BASIC_LATIN;
}

Reference