字串中帶有emoji表情處理

來源:互聯網
上載者:User

標籤:

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表情處理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.