在聊天软件,如微信,在请求好友昵称的时候,经常会遇到emoji格式的表情头像,通常我们冲后台获取到的字符串都是<span class=\"emoji emoji2122\"></span> 这样一个格式,
怎么在textview中显示出emoji表情呢?
其实很简单,我们把对应的emoji的值取出来,转换为16进制的值,直接给textview,textview就可以直接识别出来,不同版本识别的emoji是有区别的,最直接的就是android和ios。
可以直接复制EmojiUtils,调用convert就可以了,这个方法会把nickname中的emoji过滤,返回一个替换掉span的字符串回来。但是需要注意有些特殊的emoji表情是两个emoji值表示出来的,不同版本显示会有所不同。
public class EmojiUtils { public static final String EMOJI_PATTERN = "<span\\s+class\\s*=\\s*\\\\?\"emoji emoji(\\p{XDigit}+)\\\\?\"></span>"; public static String convert(String orignalName) { if (orignalName == null || orignalName.isEmpty()) { return orignalName; } Pattern p = Pattern.compile(EMOJI_PATTERN); Matcher matcher = p.matcher(orignalName); StringBuffer buffer = new StringBuffer(); while (matcher.find()) { String emojiCode = matcher.group(1); matcher.appendReplacement(buffer, getReplacement(emojiCode)); } matcher.appendTail(buffer); return buffer.toString(); } private static String getReplacement(String emojiCode) { int length = emojiCode.length(); String replacement = "?"; if (length == 4 || length == 5) { replacement = emojiCodeToUnicode(emojiCode); } else if (length == 6 || length == 8) { if (length == 6) { String start = emojiCodeToUnicode(emojiCode.substring(0, 2)); String end = emojiCodeToUnicode(emojiCode.substring(2, 6)); replacement = start + end; } else { String start = emojiCodeToUnicode(emojiCode.substring(0, 4)); String end = emojiCodeToUnicode(emojiCode.substring(4, 8)); replacement = start + end; } } else if (length == 10) { String start = emojiCodeToUnicode(emojiCode.substring(0, 5)); String end = emojiCodeToUnicode(emojiCode.substring(5, 10)); replacement = start + end; } return replacement; } private static String emojiCodeToUnicode(String emojiCode) { return new String(Character.toChars(Integer.parseInt(emojiCode, 16))); }}
时间: 2024-10-31 09:19:18