android- restrict edittext仅接受波斯语字符

时间:2017-05-22 05:16:26

标签: android

我想限制我的edittext只接受波斯语字符。像ضصثقف这样的字符。

我试过使用xml数字,但它没有用。

我该怎么办?

2 个答案:

答案 0 :(得分:0)

您可以将InputFilter用于EditText。可以将InputFilters附加到Editables以约束可以对其进行的更改。

InputFilter filter = new InputFilter() {
        public CharSequence filter(CharSequence source, int start, int end, 
            Spanned dest, int dstart, int dend) {
            for (int i = start; i < end; i++) {
                String text = String.valueOf(source.charAt(i));
                Pattern RTL_CHARACTERS = Pattern.compile("[\u0600-
                \u06FF\u0750-\u077F\u0590-\u05FF\uFE70-\uFEFF]");
                Matcher matcher = RTL_CHARACTERS.matcher(text);
                if (matcher.find()) {
                    return "";  // it's Persian
                }
            }
            return null;
        }
    };

使用此过滤器检测波斯语/波斯语字符并将其限制为edittext。使用

将此过滤器设置为EditText

editText.setFilters(new InputFilter[]{filter});

这将限制波斯语/波斯语字符

答案 1 :(得分:0)

这些代码也有帮助:

    InputFilter nameFilter = new InputFilter() {
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            for (int i = start; i < end; i++) {
                if (Character.isLetterOrDigit(source.charAt(i))) { // if digit!

                    String blockCharacterSet = getString(R.string.all_fa_words) + ' ';

                    if (blockCharacterSet.contains(String.valueOf(source.charAt(i)))) {
                        edtNameEdit.setHintTextColor(getResources().getColor(R.color.materialWhite));
                        edtNameEdit.setHint(getString(R.string.name_lastname));
                        return null;
                    } else {
                        edtNameEdit.setHintTextColor(getResources().getColor(R.color.sPink));
                        edtNameEdit.setHint(getString(R.string.name_lastname) + ' ' + getString(R.string.must_fa));
                        return edtNameEdit.getText().toString();
                    }
                } else {
                    return null;
                }
            }
            return null;
        }
    };
    edtNameEdit.setFilters(new InputFilter[]{nameFilter});
    edtNameEdit.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);