Android - 通过Html.fromHtml在TextView中的图像?

时间:2013-04-25 12:26:36

标签: java android html image textview

我想在Android中的TextView中显示图像,并认为这可以通过Html.fromHtml()实现。我找到了不同的教程,其中图像是本地资源。当我有图像的URL时,它也可以吗?如果是,有人可以给我一个例子吗?

2 个答案:

答案 0 :(得分:1)

您可以使用WebView显示图像,而不是TextView。如果您需要显示笑脸,则需要提取该关键字并替换为特定图像并绘制它。为此,您需要创建自定义视图。

答案 1 :(得分:1)

我有解决方案。放下以下代码,在文本视图中添加微笑。

private static final Factory spannableFactory = Spannable.Factory
        .getInstance();

private static final Map<Pattern, Integer> emoticons = new HashMap<Pattern, Integer>();

static {
    addPattern(emoticons, ":)", R.drawable.happy);
    addPattern(emoticons, ":(", R.drawable.sad);
    addPattern(emoticons, ":D", R.drawable.very_happy);
    // ...as many pattern you want. But make sure you have images in drawable directory
}

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;
}

执行复制粘贴后,编写以下代码以在文本视图中设置微笑。

textView.setText(getSmiledText(ActivityName.this,"Hi :) How are you...??? :D I am very :("));