如何限制EditText只接受字母数字字符

时间:2021-05-02 16:02:11

How can I restrict an EditText to accept only alphanumeric characters, with both lowercase and uppercase characters showing as uppercase in the EditText?

我如何限制EditText只接受字母数字字符,在EditText中显示为大写字母的小写字母和大写字母?

<EditText
    android:id="@+id/userInput"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:inputType="textMultiLine"
    android:minLines="3" >

    <requestFocus />
</EditText>

If a user types in lowercase "abcd", the EditText should automatically show uppercase "ABCD" without needing to restrict the keyboard to uppercase.

如果用户输入小写的“abcd”,EditText应该自动显示大写的“abcd”,而不需要将键盘限制为大写。

10 个解决方案

#1


88  

In the XML, add this:

在XML中,添加以下内容:

 android:digits="abcdefghijklmnopqrstuvwxyz1234567890 "

#2


19  

How to restrict the EditText to accept only alphanumeric characters only so that whatever lower case or upper case key that the user is typing, EditText will show upper case

如何限制EditText只接受字母数字字符,以便无论用户输入的是小写还是大写键,EditText都会显示大小写

The InputFilter solution works well, and gives you full control to filter out input at a finer grain level than android:digits. The filter() method should return null if all characters are valid, or a CharSequence of only the valid characters if some characters are invalid. If multiple characters are copied and pasted in, and some are invalid, only the valid characters should be kept.

InputFilter解决方案工作得很好,并使您能够完全控制以比android: digital更细的粒度水平过滤输入。如果所有字符都是有效的,那么filter()方法应该返回null;如果某些字符无效,则只返回有效字符的字符序列。如果多个字符被复制并粘贴进来,并且有些是无效的,那么应该只保留有效的字符。

public static class AlphaNumericInputFilter implements InputFilter {
    public CharSequence filter(CharSequence source, int start, int end,
            Spanned dest, int dstart, int dend) {

        // Only keep characters that are alphanumeric
        StringBuilder builder = new StringBuilder();
        for (int i = start; i < end; i++) {
            char c = source.charAt(i);
            if (Character.isLetterOrDigit(c)) {
                builder.append(c);
            }
        }

        // If all characters are valid, return null, otherwise only return the filtered characters
        boolean allCharactersValid = (builder.length() == end - start);
        return allCharactersValid ? null : builder.toString();
    }
}

Also, when setting your InputFilter, you must make sure not to overwrite other InputFilters set on your EditText; these could be set in XML, like android:maxLength. You must also consider the order that the InputFilters are set, they are applied in that order. Luckily, InputFilter.AllCaps already exists, so that applied with our alphanumeric filter will keep all alphanumeric text, and convert it to uppercase.

此外,在设置InputFilter时,必须确保不覆盖EditText上设置的其他InputFilter;这些可以在XML中设置,如android:maxLength。您还必须考虑InputFilters设置的顺序,它们按该顺序应用。幸运的是,InputFilter。AllCaps已经存在,因此使用我们的字母数字过滤器将保留所有字母数字文本,并将其转换为大写。

    // Apply the filters to control the input (alphanumeric)
    ArrayList<InputFilter> curInputFilters = new ArrayList<InputFilter>(Arrays.asList(editText.getFilters()));
    curInputFilters.add(0, new AlphaNumericInputFilter());
    curInputFilters.add(1, new InputFilter.AllCaps());
    InputFilter[] newInputFilters = curInputFilters.toArray(new InputFilter[curInputFilters.size()]);
    editText.setFilters(newInputFilters);

#3


9  

If you don't want much of customization a simple trick is actually from the above one with all characters you want to add in android:digits

如果您不希望进行大量的定制,那么一个简单的技巧就是使用上面的技巧,在android中添加所有的字符:数字

android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

This should work to accept alphanumeric values with Caps & Small letters.

这应该能够接受带有大写字母和小写字母的字母数字值。

#4


6  

Use this:

用这个:

android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
android:inputType="textCapCharacters"

I tried using textAllCaps="true" as suggested in a comment of accepted answer to this question but it didn't work as expected.

我试着用textAllCaps="true"来回答这个问题。

#5


4  

try This:

试试这个:

private void addFilterToUserName()
    {

        sign_up_display_name_et.setFilters(new InputFilter[] {
                new InputFilter() {
                    public CharSequence filter(CharSequence src, int start,
                                               int end, Spanned dst, int dstart, int dend) {
                        if(src.equals("")){ // for backspace
                            return src;
                        }
                        if(src.toString().matches("[a-zA-Z 0-9]+")){
                            return src;
                        }
                        return "";
                    }
                }
        });
    }

#6


2  

You do not want to write any regular expression for this you can just add XML properties to your Edit text

您不希望编写任何正则表达式,您只需将XML属性添加到编辑文本中即可。

android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
android:inputType="textCapCharacters"

Tested Working Perfectly for PAN Card validation.

经测试,适用于泛卡验证。

#7


1  

This works for me:

这工作对我来说:

android:inputType="textVisiblePassword"

android:inputType = " textVisiblePassword "

#8


0  

For that you need to create your custom Filter and set to your EditText like this.

为此,您需要创建自定义过滤器,并将其设置为如下所示的EditText。

This will convert your alphabets to uppercase automatically.

这将自动将你的字母转换为大写。

EditText editText = (EditText)findViewById(R.id.userInput);
InputFilter myFilter = new InputFilter() {

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        try {
            Character c = source.charAt(0);
            if (Character.isLetter(c) || Character.isDigit(c)) {
                return "" + Character.toUpperCase(c);
            } else {
                return "";
            }
        } catch (Exception e) {
        }
        return null;
    }
};
editText.setFilters(new InputFilter[] { myFilter });

No additional parameters to set in xml file.

不需要在xml文件中设置其他参数。

#9


0  

Programmatically, do this:

以编程方式,这样做:

mEditText.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
mEditText.setFilters(new InputFilter[] {
    new InputFilter() {   
        @Override  
        public CharSequence filter(CharSequence input, int start, int end, Spanned dst, int dstart, int dend) { 
            if (input.length() > 0 && !Character.isLetterOrDigit(input.charAt(0))) {  
                // if not alphanumeric, disregard the latest input
                // by returning an empty string 
                return ""; 
            }
            return null;
        }  
    }, new InputFilter.AllCaps()
});

Note that the call to setInputType is necessary so that we are sure that the input variable is always the last character given by the user.

注意,调用setInputType是必要的,这样我们就可以确保输入变量始终是用户给出的最后一个字符。

I have tried other solutions discussed here in SO. But many of them were behaving weird in some cases such as when you have Quick Period (Tap space bar twice for period followed by space) settings on. With this setting, it deletes one character from your input text. This code solves this problem as well.

我已经尝试过这里讨论的其他解决方法。但在某些情况下,他们中的许多人表现得很奇怪,比如当你有一个快速周期(按两次空格键,然后按空格键)设置时。通过这个设置,它从输入文本中删除一个字符。这段代码也解决了这个问题。

#10


0  

one line answer

一行的答案

XML Add this textAllCaps="true"

XML添加这个textAllCaps = " true "

do this onCreate()

做这个onCreate()

for lower case & upper case with allowing space

适用于有空格的大小写和大小写

yourEditText.setKeyListener(DigitsKeyListener.getInstance("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 "));

for lower case with allowing space (Required answer for this question)

对于允许空格的小写字母(此问题的必要答案)

yourEditText.setKeyListener(DigitsKeyListener.getInstance("abcdefghijklmnopqrstuvwxyz1234567890 "));

for upper case with allowing space

对于允许空格的大写字母

yourEditText.setKeyListener(DigitsKeyListener.getInstance("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 "));

#1


88  

In the XML, add this:

在XML中,添加以下内容:

 android:digits="abcdefghijklmnopqrstuvwxyz1234567890 "

#2


19  

How to restrict the EditText to accept only alphanumeric characters only so that whatever lower case or upper case key that the user is typing, EditText will show upper case

如何限制EditText只接受字母数字字符,以便无论用户输入的是小写还是大写键,EditText都会显示大小写

The InputFilter solution works well, and gives you full control to filter out input at a finer grain level than android:digits. The filter() method should return null if all characters are valid, or a CharSequence of only the valid characters if some characters are invalid. If multiple characters are copied and pasted in, and some are invalid, only the valid characters should be kept.

InputFilter解决方案工作得很好,并使您能够完全控制以比android: digital更细的粒度水平过滤输入。如果所有字符都是有效的,那么filter()方法应该返回null;如果某些字符无效,则只返回有效字符的字符序列。如果多个字符被复制并粘贴进来,并且有些是无效的,那么应该只保留有效的字符。

public static class AlphaNumericInputFilter implements InputFilter {
    public CharSequence filter(CharSequence source, int start, int end,
            Spanned dest, int dstart, int dend) {

        // Only keep characters that are alphanumeric
        StringBuilder builder = new StringBuilder();
        for (int i = start; i < end; i++) {
            char c = source.charAt(i);
            if (Character.isLetterOrDigit(c)) {
                builder.append(c);
            }
        }

        // If all characters are valid, return null, otherwise only return the filtered characters
        boolean allCharactersValid = (builder.length() == end - start);
        return allCharactersValid ? null : builder.toString();
    }
}

Also, when setting your InputFilter, you must make sure not to overwrite other InputFilters set on your EditText; these could be set in XML, like android:maxLength. You must also consider the order that the InputFilters are set, they are applied in that order. Luckily, InputFilter.AllCaps already exists, so that applied with our alphanumeric filter will keep all alphanumeric text, and convert it to uppercase.

此外,在设置InputFilter时,必须确保不覆盖EditText上设置的其他InputFilter;这些可以在XML中设置,如android:maxLength。您还必须考虑InputFilters设置的顺序,它们按该顺序应用。幸运的是,InputFilter。AllCaps已经存在,因此使用我们的字母数字过滤器将保留所有字母数字文本,并将其转换为大写。

    // Apply the filters to control the input (alphanumeric)
    ArrayList<InputFilter> curInputFilters = new ArrayList<InputFilter>(Arrays.asList(editText.getFilters()));
    curInputFilters.add(0, new AlphaNumericInputFilter());
    curInputFilters.add(1, new InputFilter.AllCaps());
    InputFilter[] newInputFilters = curInputFilters.toArray(new InputFilter[curInputFilters.size()]);
    editText.setFilters(newInputFilters);

#3


9  

If you don't want much of customization a simple trick is actually from the above one with all characters you want to add in android:digits

如果您不希望进行大量的定制,那么一个简单的技巧就是使用上面的技巧,在android中添加所有的字符:数字

android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

This should work to accept alphanumeric values with Caps & Small letters.

这应该能够接受带有大写字母和小写字母的字母数字值。

#4


6  

Use this:

用这个:

android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
android:inputType="textCapCharacters"

I tried using textAllCaps="true" as suggested in a comment of accepted answer to this question but it didn't work as expected.

我试着用textAllCaps="true"来回答这个问题。

#5


4  

try This:

试试这个:

private void addFilterToUserName()
    {

        sign_up_display_name_et.setFilters(new InputFilter[] {
                new InputFilter() {
                    public CharSequence filter(CharSequence src, int start,
                                               int end, Spanned dst, int dstart, int dend) {
                        if(src.equals("")){ // for backspace
                            return src;
                        }
                        if(src.toString().matches("[a-zA-Z 0-9]+")){
                            return src;
                        }
                        return "";
                    }
                }
        });
    }

#6


2  

You do not want to write any regular expression for this you can just add XML properties to your Edit text

您不希望编写任何正则表达式,您只需将XML属性添加到编辑文本中即可。

android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
android:inputType="textCapCharacters"

Tested Working Perfectly for PAN Card validation.

经测试,适用于泛卡验证。

#7


1  

This works for me:

这工作对我来说:

android:inputType="textVisiblePassword"

android:inputType = " textVisiblePassword "

#8


0  

For that you need to create your custom Filter and set to your EditText like this.

为此,您需要创建自定义过滤器,并将其设置为如下所示的EditText。

This will convert your alphabets to uppercase automatically.

这将自动将你的字母转换为大写。

EditText editText = (EditText)findViewById(R.id.userInput);
InputFilter myFilter = new InputFilter() {

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        try {
            Character c = source.charAt(0);
            if (Character.isLetter(c) || Character.isDigit(c)) {
                return "" + Character.toUpperCase(c);
            } else {
                return "";
            }
        } catch (Exception e) {
        }
        return null;
    }
};
editText.setFilters(new InputFilter[] { myFilter });

No additional parameters to set in xml file.

不需要在xml文件中设置其他参数。

#9


0  

Programmatically, do this:

以编程方式,这样做:

mEditText.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
mEditText.setFilters(new InputFilter[] {
    new InputFilter() {   
        @Override  
        public CharSequence filter(CharSequence input, int start, int end, Spanned dst, int dstart, int dend) { 
            if (input.length() > 0 && !Character.isLetterOrDigit(input.charAt(0))) {  
                // if not alphanumeric, disregard the latest input
                // by returning an empty string 
                return ""; 
            }
            return null;
        }  
    }, new InputFilter.AllCaps()
});

Note that the call to setInputType is necessary so that we are sure that the input variable is always the last character given by the user.

注意,调用setInputType是必要的,这样我们就可以确保输入变量始终是用户给出的最后一个字符。

I have tried other solutions discussed here in SO. But many of them were behaving weird in some cases such as when you have Quick Period (Tap space bar twice for period followed by space) settings on. With this setting, it deletes one character from your input text. This code solves this problem as well.

我已经尝试过这里讨论的其他解决方法。但在某些情况下,他们中的许多人表现得很奇怪,比如当你有一个快速周期(按两次空格键,然后按空格键)设置时。通过这个设置,它从输入文本中删除一个字符。这段代码也解决了这个问题。

#10


0  

one line answer

一行的答案

XML Add this textAllCaps="true"

XML添加这个textAllCaps = " true "

do this onCreate()

做这个onCreate()

for lower case & upper case with allowing space

适用于有空格的大小写和大小写

yourEditText.setKeyListener(DigitsKeyListener.getInstance("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 "));

for lower case with allowing space (Required answer for this question)

对于允许空格的小写字母(此问题的必要答案)

yourEditText.setKeyListener(DigitsKeyListener.getInstance("abcdefghijklmnopqrstuvwxyz1234567890 "));

for upper case with allowing space

对于允许空格的大写字母

yourEditText.setKeyListener(DigitsKeyListener.getInstance("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 "));