android中EditText过滤Emoji表情

Emoji表情编码

有关Emoji的表情编码参见Wikipedia
Emoji -Wikipedia

判断是否含有emoji表情

1
2
3
4
5
6
7
8
9
10
11
12
/**
* @param CharSequence source
* 判断是否含有emoji表情
*/
public static boolean isHasEmoji(CharSequence source) {
Pattern emoji = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]", Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
Matcher emojiMatcher = emoji.matcher(source);
if (emojiMatcher.find()) {
return true;
}
return false;
}

新建一个InputFilter 过滤emoji表情和限制字符串长度

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* This filter will constrain edits not to make the length of the text
* greater than the specified length.Restrict input expression.
*/
public static class LengthAndEmoijFilter implements InputFilter {
public LengthAndEmoijFilter(int max) {
mMax = max;
}
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
//判断是否含有emoji表情
if (isHasEmoji(source)) {
return "";
}
int keep = mMax - (dest.length() - (dend - dstart));
if (keep <= 0) {
return "";
} else if (keep >= end - start) {
return null; // keep original
} else {
keep += start;
if (Character.isHighSurrogate(source.charAt(keep - 1))) {
--keep;
if (keep == start) {
return "";
}
}
return source.subSequence(start, keep);
}
}
private int mMax;
}

在mEditText中设置过滤规则

1
2
3
private static int MAX_MESSAGE_LENGTH = 10;//规定长度大小限制为10
mEditText.setFilters(new InputFilter[]{ new UPUtils.LengthAndEmoijFilter(MAX_MESSAGE_LENGTH) });