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(); }}
时间: 2024-10-14 00:22:42