0

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

4

2 回答 2

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 :("));
于 2013-04-25T13:25:17.727 回答
1

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

于 2013-04-25T12:35:20.030 回答