字符串中带有emoji表情处理

Posted 梦见一只

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了字符串中带有emoji表情处理相关的知识,希望对你有一定的参考价值。

1:先删除字符然后解析当前字符再显示

edit.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}

@Override
public void afterTextChanged(Editable s) {
send.setEnabled(!s.toString().isEmpty());
int start = edit.getSelectionStart();
int end = edit.getSelectionEnd();
edit.removeTextChangedListener(this);
CharSequence cs = EmojiManager.parse(s.toString(), edit.getTextSize());
Toast.makeText(login.this,cs.toString(),Toast.LENGTH_SHORT).show();
edit.setText(cs, TextView.BufferType.SPANNABLE);
edit.setSelection(start, end);
edit.addTextChangedListener(this);
}
});
2:解析方法 判断每个字符的是否为表情然后做处理
public static CharSequence parse(String text, float textSize) {
if (text == null) {
return "";
}
//将字符串转换为数组
final char[] chars = text.toCharArray();
final SpannableStringBuilder ssb = new SpannableStringBuilder(text);

int codePoint;
boolean isSurrogatePair;
for (int i = 0; i < chars.length; i++) {
if (Character.isHighSurrogate(chars[i])) {
continue;
} else if (Character.isLowSurrogate(chars[i])) {
if (i > 0 && Character.isSurrogatePair(chars[i - 1], chars[i])) {
codePoint = Character.toCodePoint(chars[i - 1], chars[i]);
isSurrogatePair = true;
} else {
continue;
}
} else {
codePoint = (int) chars[i];
isSurrogatePair = false;
}

if (emojiCodeList.contains(codePoint)) {
Bitmap bitmap = BitmapFactory.decodeResource(gContext.getResources(), getResourceByCode(codePoint));
BitmapDrawable bmpDrawable = new BitmapDrawable(gContext.getResources(), bitmap);
bmpDrawable.setBounds(0, 0, (int) textSize, (int) textSize);
CenterImageSpan imageSpan = new CenterImageSpan(bmpDrawable);
ssb.setSpan(imageSpan, isSurrogatePair ? i - 1 : i, i + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
return ssb;
}

private static class CenterImageSpan extends ImageSpan {

public CenterImageSpan(Drawable draw) {
super(draw);
}

@Override
public void draw(Canvas canvas, CharSequence text, int start, int end, float x,
int top, int y, int bottom, Paint paint) {
Drawable b = getDrawable();
Paint.FontMetricsInt fm = paint.getFontMetricsInt();
int transY = ((bottom - top) - getDrawable().getBounds().bottom) / 2 + top;
canvas.save();
canvas.translate(x, transY);
b.draw(canvas);
canvas.restore();
}
}

以上是关于字符串中带有emoji表情处理的主要内容,如果未能解决你的问题,请参考以下文章

MYSQL 写入emoji表情字符处理

安卓怎么处理emoji表情提交给后台

emoji表情处理,emoji表情的编码解码

python 怎么过滤 emoji 表情符号

转移动前端手机输入法自带emoji表情字符处理

android怎样过滤字符串中的emoji表情