使用 TextWatcher 验证 EditText

发布于 2024-10-03 19:16:41 字数 1243 浏览 3 评论 0原文

我有一个带有 EditText 和一个按钮的对话框。此 EditText 将命名我将创建的数据库表,因此对其进行验证至关重要。所以我想提出两个问题:

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

2) 我已成功使用 TextWtacher 验证 EditText。代码如下:

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) {}
});

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

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

问题是...如何替换 s 文本?

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

I have a Dialog with a EditText and a button. This EditText will name the database table I will create so its of the utmost importance it is validated. So i would like to pose 2 questions:

1) This is quite simple, but i couldn't fin it anywhere: what characters can a database table name accept? Can it accept numbers? And can a number be the first character?

2) I've managed to validate the EditText using TextWtacher. Here's the code:

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) {}
});

Currently, if the user inserts any character other than lowercase letters and numbers, the textbox is cleared.
If I uncomment s.insert(0, filtered_str); in order to to replace the EditText with the filtered string, my app hangs. And guess what I find in the debug?

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

The question is... how can I replace the s text?

-> s.replace(0, s.toString().length(), filtered_str); (remove s.clear, of course) doesn't seem to work either.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

荒芜了季节 2024-10-10 19:16:41
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);
                }
         }
};
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);
                }
         }
};
冰火雁神 2024-10-10 19:16:41

经过一番绞尽脑汁,我终于找到了解决方案。似乎 s.append(filtered_str) 在 s.clear() 工作之后。不知道为什么以前不起作用。

After some headbanging, I finally found the solution. Seems s.append(filtered_str) after s.clear() works. Dunno why it hasn't work before.

不寐倦长更 2024-10-10 19:16:41

嘿!
我正在尝试类似的方法,强制输入文本全部小写; s.clear() 后跟 s.append() 对我来说也(或仍然)导致 StackOverflow。

想知道为什么 Android 会让我们千方百计强制转换为小写吗?

由于使用 TextWatcher 对我来说崩溃了(没错......而且我不知道如何工作跨度),所以我查看了 TransformationMethod。

第一次尝试是在 EditText 上执行内联 TransformationMethod,如下所示:

et.setTransformationMethod(new TransformationMethod() {

        public void onFocusChanged(View view, CharSequence sourceText, boolean focused, int direction,
                Rect previouslyFocusedRect) {
        }

        public CharSequence getTransformation(CharSequence source, View view) {
            String ret = source.toString().toLowerCase();
            System.out.println(ret);
            return ret;
        }
    });

当我在 ET 中输入单个字符时,这会导致由于 IndexArrayOutOfBounds 而崩溃...无法弄清楚原因。

所以,我检查了PasswordTransformation 的代码,然后检查了ReplacementTransformation 的代码——两者看起来都非常复杂,我不想为所有这些“东西”烦恼。

然后检查了很简单的 SinglelineTransformation 子类...所以我创建了 LowerCaseTransformation 作为 ReplacementTransformation 的子类,如下所示:

public class LowerCaseReplacement extends ReplacementTransformationMethod {
private static final char[] ORIG = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
        'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
private static final char[] REPS = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
        'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
private static LowerCaseReplacement singleton;

@Override
protected char[] getOriginal() {
    return ORIG;
}

@Override
protected char[] getReplacement() {
    return REPS;
}

public static LowerCaseReplacement getInstance() {
    if (singleton == null)
        singleton = new LowerCaseReplacement();
    return singleton;
}

}

并将此 xform 添加到 et... 如 et.setTransformationMethod(LowerCaseReplacement.getInstnace())...

中作品!!

如果谁有更好的解决办法,请赐教!

hey!
i'm trying similar thing with forcing the input text to be all lowercase; s.clear() followed by s.append() causes a StackOverflow for me too (or still).

wonder why Android puts us thru' hoops to force conversion to lowercase ?

Since using TextWatcher was crashing for me (rightly so... and i couldn't figure out how to work spans), i looked at TransformationMethod.

1st try was to do an inline TransformationMethod on the EditText with something like this:

et.setTransformationMethod(new TransformationMethod() {

        public void onFocusChanged(View view, CharSequence sourceText, boolean focused, int direction,
                Rect previouslyFocusedRect) {
        }

        public CharSequence getTransformation(CharSequence source, View view) {
            String ret = source.toString().toLowerCase();
            System.out.println(ret);
            return ret;
        }
    });

This caused crash due to IndexArrayOutOfBounds as soon as i typed a single char in the ET... could not figure out why.

So, i checked the code for PasswordTransformation and then ReplacementTransformation -- both seem very complicated and i didn't want to bother with all that ?stuff?.

Then in checked out the SinglelineTransformation subclass which was simple... so i created LowerCaseTransformation as subclass of ReplacementTransformation as follows:

public class LowerCaseReplacement extends ReplacementTransformationMethod {
private static final char[] ORIG = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
        'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
private static final char[] REPS = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
        'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
private static LowerCaseReplacement singleton;

@Override
protected char[] getOriginal() {
    return ORIG;
}

@Override
protected char[] getReplacement() {
    return REPS;
}

public static LowerCaseReplacement getInstance() {
    if (singleton == null)
        singleton = new LowerCaseReplacement();
    return singleton;
}

}

and adding this xform to et... as in et.setTransformationMethod(LowerCaseReplacement.getInstnace())...

This works!!

If anyone has a better solution, then please enlighten!

风流物 2024-10-10 19:16:41

问题是,当您调用插入方法时,会再次调用文本更改方法。这会导致恶性循环,从而导致堆栈溢出。您可以通过不替换格式正确的字符串来避免这种情况。

The problem is that when you call the insert method, the text changed method is called again. This results in a vicious circle, thus the stack overflow. You can avoid this by not replacing a string that is properly formatted.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文