[安卓项目学习笔记]将文本中的emoji字符处理为表情图片

本文介绍了一个名为SpanStringUtils的工具类,该工具类可以将文本中的emoji字符替换为相应的表情图片。通过正则表达式匹配文本中的emoji字符,并利用EmotionUtils获取对应的图片资源,最后通过ImageSpan将表情图片嵌入到文本中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SpanStringUtils 工具类
用途:将文本中的emoji字符处理为表情图片
(利用正则,取出特定的字符并且找到相应的图片,再将图片导入ImageSpan ,最终使用spannableString将ImageSpan存入)

public class SpanStringUtils {

    public static SpannableString getEmotionContent(int emotion_map_type,final Context context, final TextView tv, String source) {
        SpannableString spannableString = new SpannableString(source);
        Resources res = context.getResources();

        String regexEmotion = "\\[([\u4e00-\u9fa5\\w])+\\]";
        Pattern patternEmotion = Pattern.compile(regexEmotion);
        Matcher matcherEmotion = patternEmotion.matcher(spannableString);

        while (matcherEmotion.find()) {
            // 获取匹配到的具体字符
            String key = matcherEmotion.group();
            // 匹配字符串的开始位置
            int start = matcherEmotion.start();
            // 利用表情名字获取到对应的图片
            Integer imgRes = EmotionUtils.getImgByName(emotion_map_type,key);
            if (imgRes != null) {
                // 压缩表情图片
                int size = (int) tv.getTextSize()*13/10;
                Bitmap bitmap = BitmapFactory.decodeResource(res, imgRes);
                Bitmap scaleBitmap = Bitmap.createScaledBitmap(bitmap, size, size, true);

                ImageSpan span = new ImageSpan(context, scaleBitmap);
                spannableString.setSpan(span, start, start + key.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        return spannableString;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值