在Android中显示表情图标

我的IM应用程序必须支持表情图标。 它们是GIF并具有文本表示,如果用户select其中的一个,则在input框中使用它们。 但是我希望在发送完成后将它们显示为图像。目前,我的自定义数组适配器在一行的TextView中显示发送的消息。

什么是适当的方法来dynamic显示图像的基础上发生的文字表示? 我是否必须search表情文本,如果发现,从布局中删除TextView(relativeLayout最适合?),并添加一个TextView与IM的开始,一个ImageView与表情和另一个TextView。 如果同时发送更多的表情符号可能会变得混乱。

有一个更容易和更合乎逻辑的方法吗?

我会尝试使用正则expression式来用<img>标签replace每个表情符号的所有出现。 然后, 通过Html.fromHtml()将该HTML转换为SpannedStringSpannedString可以在TextViewsetText()调用中使用。

我认为构buildSpannable会更有用。

 private static final Factory spannableFactory = Spannable.Factory .getInstance(); private static final Map<Pattern, Integer> emoticons = new HashMap<Pattern, Integer>(); static { addPattern(emoticons, ":)", R.drawable.emo_im_happy); addPattern(emoticons, ":-)", R.drawable.emo_im_happy); // ... } private static void addPattern(Map<Pattern, Integer> map, String smile, int resource) { map.put(Pattern.compile(Pattern.quote(smile)), resource); } public static boolean addSmiles(Context context, Spannable spannable) { boolean hasChanges = false; for (Entry<Pattern, Integer> entry : emoticons.entrySet()) { Matcher matcher = entry.getKey().matcher(spannable); while (matcher.find()) { boolean set = true; for (ImageSpan span : spannable.getSpans(matcher.start(), matcher.end(), ImageSpan.class)) if (spannable.getSpanStart(span) >= matcher.start() && spannable.getSpanEnd(span) <= matcher.end()) spannable.removeSpan(span); else { set = false; break; } if (set) { hasChanges = true; spannable.setSpan(new ImageSpan(context, entry.getValue()), matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } } return hasChanges; } public static Spannable getSmiledText(Context context, CharSequence text) { Spannable spannable = spannableFactory.newSpannable(text); addSmiles(context, spannable); return spannable; } 

Actualy这个代码基于本地Html类的来源。

编辑:更新版本有戏剧性的速度提高。