开发者

Take only one character from user in Android

开发者 https://www.devze.com 2023-03-27 06:26 出处:网络
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 th开发者_如何学Gois problem? Thanks in advance..You

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 th开发者_如何学Gois problem? Thanks in advance..


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消