使用TextWatcher进行EditText验证

Tiv*_*vie 7 java string android textwatcher android-edittext

我有一个带有a EditText和按钮的Dialog .这EditText将命名我将创建的数据库表,以便验证它的最重要性.所以我想提出2个问题:

1)这很简单,但我无法在任何地方找到它:数据库表名称可以接受哪些字符?可以接受号码吗?并且数字可以是第一个字符吗?

2)我设法验证EditText使用TextWtacher.这是代码:

et_name.addTextChangedListener(new TextWatcher() {

public void afterTextChanged(Editable s) {

    String filtered_str = s.toString();

        if (filtered_str.matches(".*[^a-z^0-9].*")) {

        filtered_str = filtered_str.replaceAll("[^a-z^0-9]", "");

        s.clear();

        // s.insert(0, filtered_str);

        Toast.makeText(context,
            "Only lowercase letters and numbers are allowed!",
            Toast.LENGTH_SHORT).show();

    }

}

    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

    public void onTextChanged(CharSequence s, int start, int before, int count) {}
});
Run Code Online (Sandbox Code Playgroud)

目前,如果用户插入除小写字母和数字以外的任何字符,则清除文本框.如果我取消注释s.insert(0, filtered_str);以使用过滤后的字符串替换EditText,我的应用程序将挂起.猜猜我在调试中发现了什么?

错误/ AndroidRuntime(2454):java.lang.StackOverflowError = D.

问题是......我怎样才能替换s文本?

- > s.replace(0, s.toString().length(), filtered_str);(删除s.clear,当然)似乎也不起作用.

小智 8

private TextWatcher listenerTextChangedFiltro = new TextWatcher() {
        public void afterTextChanged(Editable editable) {

                final String textoFiltrado = StaticString.filterTextCustom(String.valueOf(editable.toString().toLowerCase()));
                if (!textoFiltrado.equals(editable.toString().toLowerCase())) {
                    editable.clear();
                    editable.append(textoFiltrado);
                }
         }
};
Run Code Online (Sandbox Code Playgroud)


Tiv*_*vie 6

经过一番轰动,我终于找到了解决方案.在s.clear()工作之后似乎s.append(filtered_str).不知道为什么之前没有工作.

  • 经过1小时的搜索,我发现你的答案对我有用也谢谢蒂维...... (2认同)