Android 中仅获取用户的一个字符

发布于 2024-11-28 18:46:30 字数 61 浏览 3 评论 0原文

我希望用户只输入一个字符。我想为每个字母都制作按钮,但这没用。你能推荐一些东西来解决这个问题吗?提前致谢..

I want user to enter just one character. I thought to make buttons for every letter, but this is useless. Could you recommend something to overcome this problem? Thanks in advance..

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

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

发布评论

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

评论(2

记忆之渊 2024-12-05 18:46:30

您可以使用 InputFilter.LengthFilter 来限制字符数可以输入到文本字段和自定义 InputFilter 来限制允许使用的字符;这对我来说听起来是最简单的方法。

这是一个例子:

EditText myTextField = (EditText) findViewById(R.id.my_text);

InputFilter validCharsInputFilter = new InputFilter() {

        @Override
        public CharSequence filter(CharSequence source, int start, int end,
                Spanned dest, int dstart, int dend) {

            // Loop through characters being inserted
            for (int i = start; i < end; i++) {

                // If it is not a letter 
                if (!Character
                        .isLetter(source.charAt(i))) {

                    // Return empty string - as char not allowed
                    return "";
                }
            }

            // If we've got this far, then return null to accept string
            return null;
        }
    };

myTextField.setFilters(
        new InputFilter[] { new InputFilter.LengthFilter(1), validCharsInputFilter });

You can use an InputFilter.LengthFilter to limit the number of characters that can be entered into a text field and a custom InputFilter to restrict the characters that are allowed; which sounds like the simplest approach to me.

Here's an example:

EditText myTextField = (EditText) findViewById(R.id.my_text);

InputFilter validCharsInputFilter = new InputFilter() {

        @Override
        public CharSequence filter(CharSequence source, int start, int end,
                Spanned dest, int dstart, int dend) {

            // Loop through characters being inserted
            for (int i = start; i < end; i++) {

                // If it is not a letter 
                if (!Character
                        .isLetter(source.charAt(i))) {

                    // Return empty string - as char not allowed
                    return "";
                }
            }

            // If we've got this far, then return null to accept string
            return null;
        }
    };

myTextField.setFilters(
        new InputFilter[] { new InputFilter.LengthFilter(1), validCharsInputFilter });
橘寄 2024-12-05 18:46:30

您可以在其他解决方案中创建一个字段并将事件处理程序设置为一次仅接受一个字符。

这与该问题非常接近:Validation on Edit Text

You could among other solutions make a field and set your event handler to only accept one character at the time.

This is very close to that question: Validation on Edit Text

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