如何使用 InputFilter 限制 Android 中 EditText 中的字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3349121/
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 09:50:30  来源:igfitidea点击:

How do I use InputFilter to limit characters in an EditText in Android?

androidandroid-edittext

提问by Tim Wayne

I want to restrict the chars to 0-9, a-z, A-Z and spacebar only. Setting inputtype I can limit to digits but I cannot figure out the ways of Inputfilter looking through the docs.

我想将字符限制为 0-9、az、AZ 和空格键。设置 inputtype 我可以限制为数字,但我无法弄清楚 Inputfilter 查看文档的方式。

回答by moonlightcheese

I found this on another forum. Works like a champ.

我在另一个论坛上找到了这个。像冠军一样工作。

InputFilter filter = new InputFilter() {
    public CharSequence filter(CharSequence source, int start, int end,
            Spanned dest, int dstart, int dend) {
        for (int i = start; i < end; i++) {
            if (!Character.isLetterOrDigit(source.charAt(i))) {
                return "";
            }
        }
        return null;
    }
};
edit.setFilters(new InputFilter[] { filter });

回答by ?ukasz Sromek

InputFilters are a little complicated in Android versions that display dictionary suggestions. You sometimes get a SpannableStringBuilder, sometimes a plain Stringin the sourceparameter.

InputFilters 在显示字典建议的 Android 版本中有点复杂。你有时会在参数中得到一个SpannableStringBuilder,有时是一个普通Stringsource

The following InputFiltershould work. Feel free to improve this code!

以下InputFilter应该工作。随意改进此代码!

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

        if (source instanceof SpannableStringBuilder) {
            SpannableStringBuilder sourceAsSpannableBuilder = (SpannableStringBuilder)source;
            for (int i = end - 1; i >= start; i--) { 
                char currentChar = source.charAt(i);
                 if (!Character.isLetterOrDigit(currentChar) && !Character.isSpaceChar(currentChar)) {    
                     sourceAsSpannableBuilder.delete(i, i+1);
                 }     
            }
            return source;
        } else {
            StringBuilder filteredStringBuilder = new StringBuilder();
            for (int i = start; i < end; i++) { 
                char currentChar = source.charAt(i);
                if (Character.isLetterOrDigit(currentChar) || Character.isSpaceChar(currentChar)) {    
                    filteredStringBuilder.append(currentChar);
                }     
            }
            return filteredStringBuilder.toString();
        }
    }
}

回答by Florian Fr?hlich

much easier:

容易得多:

<EditText
    android:inputType="text"
    android:digits="0,1,2,3,4,5,6,7,8,9,*,qwertzuiopasdfghjklyxcvbnm" />

回答by Kamil Seweryn

None of posted answers did work for me. I came with my own solution:

没有一个已发布的答案对我有用。我带来了自己的解决方案:

InputFilter filter = new InputFilter() {
    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        boolean keepOriginal = true;
        StringBuilder sb = new StringBuilder(end - start);
        for (int i = start; i < end; i++) {
            char c = source.charAt(i);
            if (isCharAllowed(c)) // put your condition here
                sb.append(c);
            else
                keepOriginal = false;
        }
        if (keepOriginal)
            return null;
        else {
            if (source instanceof Spanned) {
                SpannableString sp = new SpannableString(sb);
                TextUtils.copySpansFrom((Spanned) source, start, sb.length(), null, sp, 0);
                return sp;
            } else {
                return sb;
            }           
        }
    }

    private boolean isCharAllowed(char c) {
        return Character.isLetterOrDigit(c) || Character.isSpaceChar(c);
    }
}
editText.setFilters(new InputFilter[] { filter });

回答by Mohamed Ibrahim

Use this its work 100% your need and very simple.

使用它的工作 100% 您的需要并且非常简单。

<EditText
android:inputType="textFilter"
android:digits="@string/myAlphaNumeric" />

In strings.xml

在strings.xml中

<string name="myAlphaNumeric">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789</string>

回答by Mohamed Ibrahim

To avoid Special Characters in input type

避免输入类型中的特殊字符

public static InputFilter filter = new InputFilter() {
    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        String blockCharacterSet = "~#^|$%*!@/()-'\":;,?{}=!$^';,?×÷<>{}£¥?%~`¤??_|《》??°?○●□■◇◆??▲▼??↑↓←→☆★?:-);-):-D:-(:'(:O 1234567890";
        if (source != null && blockCharacterSet.contains(("" + source))) {
            return "";
        }
        return null;
    }
};

You can set filter to your edit text like below

您可以将过滤器设置为您的编辑文本,如下所示

edtText.setFilters(new InputFilter[] { filter });

回答by mblenton

In addition to the accepted answer, it is also possible to use e.g.: android:inputType="textCapCharacters"as an attribute of <EditText>in order to only accept upper case characters (and numbers).

除了接受的答案外,还可以使用 eg:android:inputType="textCapCharacters"作为属性,<EditText>以便只接受大写字符(和数字)。

回答by Groxx

For some reason the android.text.LoginFilter class's constructor is package-scoped, so you can't directly extend it (even though it would be identical to this code). But you can extend LoginFilter.UsernameFilterGeneric! Then you just have this:

出于某种原因, android.text.LoginFilter 类的构造函数是包范围的,因此您不能直接扩展它(即使它与此代码相同)。但是你可以扩展 LoginFilter.UsernameFilterGeneric!然后你只有这个:

class ABCFilter extends LoginFilter.UsernameFilterGeneric {
    public UsernameFilter() {
        super(false); // false prevents not-allowed characters from being appended
    }

    @Override
    public boolean isAllowed(char c) {
        if ('A' <= c && c <= 'C')
            return true;
        if ('a' <= c && c <= 'c')
            return true;

        return false;
    }
}

This isn't really documented, but it's part of the core lib, and the source is straightforward. I've been using it for a while now, so far no problems, though I admit I haven't tried doing anything complex involving spannables.

这并没有真正记录在案,但它是核心库的一部分,源代码很简单。我已经使用它一段时间了,到目前为止没有问题,尽管我承认我还没有尝试过做任何涉及可跨度的复杂事情。

回答by Kailas

It's Right, the best way to go about it to fix it in the XML Layout itself using:

是的,最好的方法是使用以下方法在 XML 布局本身中修复它:

<EditText
android:inputType="text"
android:digits="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" />

as rightly pointed by Florian Fr?hlich, it works well for text views even.

正如 Florian Fr?hlich 正确指出的那样,它甚至适用于文本视图。

<TextView
android:inputType="text"
android:digits="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" />

Just a word of caution, the characters mentioned in the android:digitswill only be displayed, so just be careful not to miss any set of characters out :)

请注意, 中提到的字符android:digits只会显示出来,所以请注意不要错过任何一组字符:)

回答by Swifty McSwifterton

This simple solution worked for me when I needed to prevent the user from entering empty strings into an EditText. You can of course add more characters:

当我需要防止用户在 EditText 中输入空字符串时,这个简单的解决方案对我有用。您当然可以添加更多字符:

InputFilter textFilter = new InputFilter() {

@Override

public CharSequence filter(CharSequence c, int arg1, int arg2,

    Spanned arg3, int arg4, int arg5) {

    StringBuilder sbText = new StringBuilder(c);

    String text = sbText.toString();

    if (text.contains(" ")) {    
        return "";   
    }    
    return c;   
    }   
};

private void setTextFilter(EditText editText) {

    editText.setFilters(new InputFilter[]{textFilter});

}