如何在编辑文本中检测西里尔文本?

时间:2015-09-25 10:27:15

标签: android character-encoding android-edittext cyrillic

我需要保护在我的申请中输入西里尔文本。

是否有一些方法如何检测editText中输入符号的编码?

2 个答案:

答案 0 :(得分:2)

<强>解决方案:

您需要在EditText上投放InputFilter

示例:

EditText

上设置过滤器
etNonCyrillic = (EditText) findViewById(R.id.etNonCyrillic );
etNonCyrillic .setFilters(new InputFilter[]{cyrillicFilter});

实施cyrillicFilter

    public static InputFilter cyrillicFilter = new InputFilter() {
    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        boolean keepOriginal = true;
        StringBuilder sb = new StringBuilder(end - start);
        for (int i = start; i < end; i++) {
            char c = source.charAt(i);
            if (!isCyrillicCharacter(c))
            {
                sb.append(c);
            }
            else
            {
                keepOriginal = false;
            }
        }
        if (keepOriginal)
            return null;
        else {
            if (source instanceof Spanned) {
                SpannableString sp = new SpannableString(sb);
                TextUtils.copySpansFrom((Spanned) source, start, sb.length(), null, sp, 0);
                return sp;
            } else {
                return sb;
            }           
        }
    }

    @SuppressLint("NewApi")
    private boolean isCyrillicCharacter(char c)
    {
        boolean isPriorToKitkat = android.os.Build.VERSION.SDK_INT<19;
        UnicodeBlock block = UnicodeBlock.of(c);
        boolean isCyrillicCharacter = (block.equals(UnicodeBlock.CYRILLIC) || block.equals(UnicodeBlock.CYRILLIC_SUPPLEMENTARY) || (isPriorToKitkat?false:(block.equals(UnicodeBlock.CYRILLIC_EXTENDED_A) || block.equals(UnicodeBlock.CYRILLIC_EXTENDED_B))));
        return isCyrillicCharacter;
    }
};

答案 1 :(得分:0)

Kotlin中的解决方案,可防止用户使用西里尔字母和希腊字母保存详细信息

 fun isOnlyLatinLetters(string: String?): Boolean {
    if (string == null) return false
    return !(CYRILLIC.containsMatchIn(string)
      || GREEK.containsMatchIn(string))
  }

  private val CYRILLIC = Pattern.compile("[Ѐ-ӿ]").toRegex()
  private val GREEK = Pattern.compile("[Ͱ-Ͽ]").toRegex()