如何通过android中的软键盘以编程方式将我的EditText输入限制为一些特殊字符,如反斜杠(/)、波浪号(~)等

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

How can restrict my EditText input to some special character like backslash(/),tild(~) etc by soft keyboard in android programmatically

androidandroid-edittextcharacterandroid-softkeyboard

提问by jagdish

I am developing an application for keyboard, but i am geting an issue. I want to restrict/block some special character from soft keyboard in EditText in android programmatically.

我正在开发键盘应用程序,但遇到问题。我想以编程方式在 android 中的 EditText 中限制/阻止软键盘中的一些特殊字符。

So, Is there any way i can restrict any special character input in edit text in android.

那么,有什么办法可以限制在android中编辑文本中的任何特殊字符输入。

If anyone have idea,Please reply.

如果有人有想法,请回复。

Thanks in advance.

提前致谢。

回答by Biraj Zalavadia

Try this may works for you

试试这可能对你有用

public class MainActivity extends Activity {

    private EditText editText;
    private String blockCharacterSet = "~#^|$%&*!";

    private InputFilter filter = new InputFilter() {

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

            if (source != null && blockCharacterSet.contains(("" + source))) {
                return "";
            }
            return null;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editText = (EditText) findViewById(R.id.editText);
        editText.setFilters(new InputFilter[] { filter });
    }

}

回答by Solenya

This should work:

这应该有效:

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

Or if you prefer the easy way:

或者,如果您更喜欢简单的方法:

<EditText android:inputType="text" android:digits="0123456789*,qwertzuiopasdfghjklyxcvbnm" />

回答by Thirupathi

If you want to add spaces you can give space after the last digit.

如果你想添加空格,你可以在最后一位数字后给空格。

  android:digits="0123456789qwertzuiopasdfghjklyxcvbnm "

回答by i.n.e.f

check thislink which shows How to restrict special characters from an Android EditText field?

检查链接,其中显示了如何限制 Android EditText 字段中的特殊字符?

Try this code android:digits="abcde.....012345789"i guess this is the easiest way to do.Hope this help you.

试试这个代码, android:digits="abcde.....012345789"我想这是最简单的方法。希望这对你有帮助。

回答by Tara

Its late but may be helpfull for others. Instead of programaticaly, you can go with xml attribute. It may be the case that in Single layout you have many editText, out of which you wanna restrict special characters only in one EditText. So defining in xml will help you out. Here is the code to restrict special Characters by allowing them to only enter alphabets and numbers like below

它晚了,但可能对其他人有帮助。您可以使用 xml 属性代替编程。可能的情况是,在单一布局中,您有许多 editText,其中您只想将特殊字符限制在一个 EditText 中。所以在 xml 中定义会帮助你。这是通过允许特殊字符仅输入如下所示的字母和数字来限制特殊字符的代码

<EditText
     android:id="@+id/editText"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:textSize="@dimen/text10"
     android:singleLine="true"
     android:maxLines="1"
     android:maxLength="16"
     android:digits="abcdefghijklmnopqrstuvwxyz0123456789"/>

回答by Hitesh Bisht

For those who might be facing issues while adding space please add a blank space with all the alphabets. Below is an example Also you should know that user won't be able to add a new line in this case.

对于那些在添加空间时可能遇到问题的人,请添加一个包含所有字母的空格。下面是一个示例 另外,您应该知道在这种情况下用户将无法添加新行。

            <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="text"
            android:digits="0123456789,a bcdefghijklmnopqrstuvwxyz"
            android:maxLines="1"
            android:singleLine="true" />

回答by Upendranath Reddy

First need to add DigitsKeyListener for allowing characters and then setRawInputType to edittext field

首先需要添加 DigitsKeyListener 允许字符,然后 setRawInputType 到 edittext 字段

edit_field.setKeyListener(DigitsKeyListener.getInstance("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"));


edit_field.setRawInputType(InputType.TYPE_TEXT_VARIATION_PERSON_NAME);

回答by Looking Forward

You can create regular expression and check it on onTextChanged method

您可以创建正则表达式并在 onTextChanged 方法上检查它

yourEditText.addTextChangedListener(new TextWatcher() {

          public void afterTextChanged(Editable s) {

            // you can call or do what you want with your EditText here
            yourEditText. ... 

          }

          public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

          public void onTextChanged(CharSequence s, int start, int before, int count) {}
       });

回答by Prashant Jajal

you can prevent for typing special character:

您可以防止输入特殊字符:

yourEditText.addTextChangedListener(new TextWatcher() {
      CharSequence previous;
      public void afterTextChanged(Editable s) {
        if(s.toString().contains("&^%$#*&(")){
              s.clear();
              s.append(previous.toString());
        }
      }

      public void beforeTextChanged(CharSequence s, int start, int count, int after) {    
            previous = s;
      }

      public void onTextChanged(CharSequence s, int start, int before, int count) {}
   });

回答by Marcin Jedynak

Unfortunately the accepted solution doesn't work in all the cases. The proper solution would be to use the following InputFilter:

不幸的是,接受的解决方案并不适用于所有情况。正确的解决方案是使用以下内容InputFilter

private InputFilter filter = new InputFilter() {
    // An example pattern that restricts the input only to the lowercase letters
    private static final Pattern restrictedChars = Pattern.compile("[a-z]*")

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        final CharSequence replacementText = source.subSequence(start, end);
        final CharSequence replacedText = dest.subSequence(dstart, dend);

        if (source == null || restrictedChars.matcher(replacementText).matches()) {
            return null; // Accept the original replacement
        }

        return replacedText; // Keep the original text
    }
};

This solution differs from the accepted one in that it solves the following problems:

该解决方案与公认的解决方案不同,它解决了以下问题:

  • only a subsequence of the source is the replacement, not the full source
  • source doesn't necessarily include only the newly typed text, sometimes it is the full text typed so-far
  • 只有源的子序列是替换,而不是完整的源
  • 来源不一定只包括新输入的文本,有时它是迄今为止输入的全文