2015-09-25 62 views
2

我需要保護在我的應用程序中輸入西里爾文本。如何檢測編輯文本中的西里爾文字?

是否有某種方法可以檢測editText中輸入符號的哪種編碼?

+0

你可以檢查鍵盤的語言 – Blackbelt

+0

在這裏我必須把它?在textWatcher裏面或者在哪裏? –

+0

請詳細解釋你的用例。根據您的使用情況,您可以使用[this](http://stackoverflow.com/a/30631069/1529129)或者有一個正則表達式,可以使用文本查看器進行檢查。 –

回答

1

解決方案:

您需要在您的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; 
    } 
};