SoFunction
Updated on 2025-04-10

EditText in Android prohibits the input of emoticon code

Recently, when users edit information in projects, they do not want users to enter expressions. If the user enters expressions, it will cause an error to upload them to the background, so we need to make a judgment on the front end. Let’s talk about how to block expressions in EditText.

There are many such columns on the Internet, but they will fall into the pit if you accidentally, such as inheriting EditText and rewriting the addTextChangedListener() method. Maybe there were no problems when you tested it, but after the project was launched, there would be many problems, and the error rate was very high, but when viewing the Youmeng background, it seemed that it was an error in intercepting the length of the string. So it is recommended that you don’t use that method.

Because the above method is not good, you must think of other solutions. Here we think of intercepting characters entered by users through filters, which can avoid the problem of intercepting string corner marks that cross the bounds.

InputFilter inputFilter= new InputFilter() {
    Pattern emoji = ("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
        Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
      Matcher emojiMatcher = (source);
      if (()) {
        // (,"Embing emoticons is not supported", 0).show();        ("Embroidery emoticons are not supported");
        return "";
      }
      return null;
    }
  };

Then set filter for editText. Here, two filters are set for editText. The first is to block the expression, and the second is to set the limit on how many words the user enters.

//Set filter for editTextedit_name.setFilters(new InputFilter[]{inputFilter,new (12)});

Of course, I want to remind you that the blocked emojis cannot be completely blocked 100%. So in the end we can only choose to let the user fill in English, Chinese characters, and numbers. Below is the filtering code

InputFilter inputFilter=new InputFilter() {

    Pattern pattern = ("[^a-zA-Z0-9\\u4E00-\\u9FA5_]");
    @Override
    public CharSequence filter(CharSequence charSequence, int i, int i1, Spanned spanned, int i2, int i3) {
     Matcher matcher= (charSequence);
      if(!()){
        return null;
      }else{
        ("Only enter Chinese characters, English, and numbers");
        return "";
      }

    }
  };

OK, that's that simple. I hope it will be helpful to everyone's learning and I hope everyone will support me more.