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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23212439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 06:53:42  来源:igfitidea点击:

How to restrict the EditText to accept only alphanumeric characters

androidvalidationandroid-edittext

提问by user3472001

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

如何限制 aEditText只接受字母数字字符,并且小写和大写字符在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 EditTextshould automatically show uppercase "ABCD" without needing to restrict the keyboard to uppercase.

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

回答by Hashir Sheikh

In the XML, add this:

在 XML 中,添加以下内容:

 android:digits="abcdefghijklmnopqrstuvwxyz1234567890 "

回答by Steven Byle

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 InputFiltersolution works well, and gives you full control to filter out input at a finer grain level than android:digits. The filter()method should return nullif all characters are valid, or a CharSequenceof 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:digits. 如果所有字符都有效,则该filter()方法应返回nullCharSequence如果某些字符无效,则仅返回有效字符中的一个。如果复制粘贴多个字符,有的无效,则只保留有效字符。

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 InputFiltersset on your EditText; these could be set in XML, like android:maxLength. You must also consider the order that the InputFiltersare set, they are applied in that order. Luckily, InputFilter.AllCapsalready exists, so that applied with our alphanumeric filter will keep all alphanumeric text, and convert it to uppercase.

此外,在设置您的 时InputFilter,您必须确保不要覆盖InputFilters您的其他设置EditText;这些可以在 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);

回答by Ajeet Singh

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:digits 中添加的所有字符

android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

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

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

回答by thetanuj

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"按照对该问题的已接受答案的评论中的建议使用,但没有按预期工作。

回答by Sai Gopi N

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.

经测试完美适用于 PAN 卡验证。

回答by Gal Rom

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

回答by methodsignature

Minimalist Kotlin approach:

极简的 Kotlin 方法:

fun EditText.allowOnlyAlphaNumericCharacters() {
    filters = filters.plus(
        listOf(
            InputFilter { s, _, _, _, _, _->
                s.replace(Regex("[^A-Za-z0-9]"), "")
            },
            InputFilter.AllCaps()
        )
    )
}

回答by edwardaa

This works for me:

这对我有用:

android:inputType="textVisiblePassword"

android:inputType="textVisiblePassword"

回答by Biraj Zalavadia

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 文件中设置其他参数。

回答by user1506104

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 setInputTypeis necessary so that we are sure that the inputvariable is always the last character given by the user.

请注意,调用 tosetInputType是必要的,以便我们确保input变量始终是用户给出的最后一个字符。

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.

我已经尝试过这里讨论的其他解决方案。但是在某些情况下,例如当您打开“快速周期”(Tap space bar twice for period followed by space)设置时,其中许多人的行为很奇怪。使用此设置,它会从您的输入文本中删除一个字符。这段代码也解决了这个问题。