android Emoji的处理
程序员文章站
2022-04-21 10:12:41
...
1.输入监听emoji,然后拦截掉
/**
* 将系统表情转化为字符串
*
* @param s
* @return
*/
public static boolean havaEmoji(String s) {
int length = s.length();
String context = "";
//循环遍历字符串,将字符串拆分为一个一个字符
for (int i = 0; i < length; i++) {
char codePoint = s.charAt(i);
//判断字符是否是emoji表情的字符
if (isEmojiCharacter(codePoint)) {
//如果是就返回
return true;
}
}
return false;
}
/**
* 是否包含表情
*
* @param codePoint
* @return 如果不包含 返回false,包含 则返回true
*/
public static boolean isEmojiCharacter(char codePoint) {
return !((codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA)
|| (codePoint == 0xD)
|| ((codePoint >= 0x20) && (codePoint <= 0xD7FF))
|| ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) || ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF)));
//使用
mBinding.etContent.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
int index = mBinding.etContent.getSelectionStart();//获取光标位置
if (havaEmoji(editable.toString())) {//包含表情就删掉这个表情
editable.delete(index - 1, index);//删除光标前的字符
return;
}
}
});
2.不拦截掉emoji,直接约定转换,前端转成String,后台接受时转成emoji
//前台转换
/**
* 将系统表情转化为字符串
*
* @param s
* @return
*/
public static String getString(String s) {
int length = s.length();
String context = "";
//循环遍历字符串,将字符串拆分为一个一个字符
for (int i = 0; i < length; i++) {
char codePoint = s.charAt(i);
//判断字符是否是emoji表情的字符
if (isEmojiCharacter(codePoint)) {
//如果是将以大括号括起来
String emoji = "{" + Integer.toHexString(codePoint) + "}";
context = context + emoji;
continue;
}
context = context + codePoint;
}
return context;
}
/**
* 是否包含表情
*
* @param codePoint
* @return 如果不包含 返回false,包含 则返回true
*/
public static boolean isEmojiCharacter(char codePoint) {
return !((codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA)
|| (codePoint == 0xD)
|| ((codePoint >= 0x20) && (codePoint <= 0xD7FF))
|| ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) || ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF)));
}
//后台转换
/**
* 将表情描述转换成表情
*
* @param str
* @return
*/
public static String getEmoji(Context context, String str) {
String string = str;
String rep = "\\{(.*?)\\}";
Pattern p = Pattern.compile(rep);
Matcher m = p.matcher(string);
while (m.find()) {
String s1 = m.group().toString();
String s2 = s1.substring(1, s1.length() - 1);
String s3;
try {
s3 = String.valueOf((char) Integer.parseInt(s2, 16));
string = string.replace(s1, s3);
} catch (Exception e) {
e.printStackTrace();
}
}
return string;
}
上一篇: emoji表情显示问号?
下一篇: 无外键关联的2个表的查询