android中EditText过滤Emoji表情 发表于 2017-04-20 | 本文总阅读量 次 Emoji表情编码有关Emoji的表情编码参见WikipediaEmoji -Wikipedia 判断是否含有emoji表情123456789101112/** * @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表情和限制字符串长度1234567891011121314151617181920212223242526272829303132333435/** * 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中设置过滤规则123private static int MAX_MESSAGE_LENGTH = 10;//规定长度大小限制为10mEditText.setFilters(new InputFilter[]{ new UPUtils.LengthAndEmoijFilter(MAX_MESSAGE_LENGTH) });