1

我有一個EditText,其中我想只允許任何語言的字母和數字。我嘗試了XML中的android:inputTypeandroid:digitsEditText只允許字母,所有語言的數字

我一套TextWatcher試圖EDITTEXT其中onTextChanged()就像是

@Override 
    public void onTextChanged(CharSequence s, int start, int before, 
      int count) { 

     switch (et.getId()) { 
     case R.id.edtMultiLang: { 
      et.removeTextChangedListener(watcher2); 
      et.setText(s.toString().replaceAll("[^[:alpha:]0-9 ]", "")); 
      // et.setText(s.toString().replaceAll("[^A-Za-z0-9 ]", "")); 
      et.addTextChangedListener(watcher2); 
      break; 
     } 
     } 
    } 

這是工作的罰款。但是,無論何時我試圖清除文本,光標都會移動以開始處理每個字母。意思是當我清除單個字母時,光標移動開始。

如果我使用像android:digits="abcdefghijklmnopqrstuvwxyz1234567890 ",它允許我只鍵入英文字母和數字。它不允許我輸入任何其他語言的文本因爲我在這裏只給出與英文相關的字母。但我的要求是允許複製/粘貼其他語言的字母和字母。 我希望我們可以通過使用Patterns,TextWatcher和InputFilter來做到這一點。但我沒有找到更好的方法。

請讓我知道是否有任何方法來做到這一點。

+0

我找到了解決方案,在http://stackoverflow.com/questions/41953259/edittext-cursor-coming-to-start-for-every-letter-when-clear-text,但是當我粘貼文本時,光標移動到 – Srikanth

回答

1

選項你提到解決問題方便,快捷,如果你使用的過濾器您的代碼將是這樣的:

public static InputFilter filter = new InputFilter() { 
    @Override 
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { 
     String blockCharacterSet = "~#^|$%*[email protected]/()-'\":;,?{}=!$^';,?×÷<>{}€£¥₩%~`¤♡♥_|《》¡¿°•○●□■◇◆♧♣▲▼▶◀↑↓←→☆★▪:-);-):-D:-(:'(:O 1234567890"; 
     if (source != null && blockCharacterSet.contains(("" + source))) { 
      return ""; 
     } 
     return null; 
    } 
}; 

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

感謝回覆josedlujan。在這我們需要列出所有特殊字符。我們也需要考慮表情符號。 – Srikanth

+0

同時在edittext中複製,粘貼文本時,它不會限制這些被阻止的符號。 – Srikanth