【问题标题】:EditText allow only alphabets, digits of all languagesEditText 只允许字母,所有语言的数字
【发布时间】:2017-01-30 12:43:58
【问题描述】:

我有一个 EditText,我想在其中只允许任何语言的字母和数字。我尝试在 XML 中使用不同的 android:inputTypeandroid:digits

我尝试使用 set TextWatcher 来编辑其中 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 来做到这一点。但我没有找到更好的方法。

如果有什么办法,请告诉我。

【问题讨论】:

标签: android android-edittext multilingual android-textwatcher input-filter


【解决方案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 = "~#^|$%*!@/()-'\":;,?{}=!$^';,?×÷<>{}€£¥₩%~`¤♡♥_|《》¡¿°•○●□■◇◆♧♣▲▼▶◀↑↓←→☆★▪:-);-):-D:-(:'(:O 1234567890";
        if (source != null && blockCharacterSet.contains(("" + source))) {
            return "";
        }
        return null;
    }
};

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

【讨论】:

  • 感谢 josedlujan 的回复。在此我们需要列出所有特殊字符。我们还需要考虑表情符号。
  • 同时在edittext中复制、粘贴文本,也不会限制这些被屏蔽的符号。
  • 如果你快速输入,源可以包含很少的符号。上面的代码不适用于这种情况。在进行替换之前,您应该按字符拆分源代码。
猜你喜欢
  • 2019-07-26
  • 2015-02-05
  • 2014-04-11
  • 2011-11-24
  • 1970-01-01
  • 1970-01-01
  • 2018-07-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多