Android 过滤特殊字符和emoji表情

时间:2022-12-19 17:32:45

网上有很多屏蔽特殊字符和表情的例子,用起来也很简单,比如:

   //判断搜索框内容是否包含特殊字符
String limitEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@①#¥%……&*()——+|{}【】‘;:”“’。,、?]";

Pattern pattern = Pattern.compile(limitEx);
Matcher m = pattern.matcher(str);

if (m.find()) {
ToastUtil.show("不能输入特殊字符");
return groupList;
}


一般都是利用正则来判断,但是特殊字符和表情特别多 要将这些特殊字符都用正则来判断会显得多而臃肿。


在Activirty中调用:

et.addTextChangedListener(textWatcher);
setProhibitEmoji(et);

后来在项目中看到了我们经理写的顿时觉得高大上啊  
于是赶紧整理下收藏起来方便以后再用,虽然不是很明白原理,但是用起来很方便直接放进项目里调用就可以了

  public  void setProhibitEmoji(EditText et) {
InputFilter[] filters = { getInputFilterProhibitEmoji() ,getInputFilterProhibitSP()};
et.setFilters(filters);
}

public InputFilter getInputFilterProhibitEmoji() {
InputFilter filter = new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
StringBuffer buffer = new StringBuffer();
for (int i = start; i < end; i++) {
char codePoint = source.charAt(i);
if (!getIsEmoji(codePoint)) {
buffer.append(codePoint);
} else {
ToastUtil.show("群组昵称不能含有第三方表情");
i++;
continue;
}
}
if (source instanceof Spanned) {
SpannableString sp = new SpannableString(buffer);
TextUtils.copySpansFrom((Spanned) source, start, end, null,
sp, 0);
return sp;
} else {
return buffer;
}
}
};
return filter;
}


public boolean getIsEmoji(char codePoint) {
if ((codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA)
|| (codePoint == 0xD)
|| ((codePoint >= 0x20) && (codePoint <= 0xD7FF))
|| ((codePoint >= 0xE000) && (codePoint <= 0xFFFD))
|| ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF)))
return false;
return true;
}


public InputFilter getInputFilterProhibitSP() {
InputFilter filter = new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
StringBuffer buffer = new StringBuffer();
for (int i = start; i < end; i++) {
char codePoint = source.charAt(i);
if (!getIsSP(codePoint)) {
buffer.append(codePoint);
} else {
ToastUtil.show("群组昵称不能含有特殊字符");
i++;
continue;
}
}
if (source instanceof Spanned) {
SpannableString sp = new SpannableString(buffer);
TextUtils.copySpansFrom((Spanned) source, start, end, null,
sp, 0);
return sp;
} else {
return buffer;
}
}
};
return filter;
}

Android 过滤特殊字符和emoji表情
在Anctivity中调用:
Android 过滤特殊字符和emoji表情