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