是否可以在 Android TextView 中显示来自 html 的内联图像? [英] Is it possible to display inline images from html in an Android TextView?

查看:18
本文介绍了是否可以在 Android TextView 中显示来自 html 的内联图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下 HTML:

<p>这是文本,这是图像 <img src="http://www.example.com/image.jpg"/>.</p>

是否可以进行图像渲染?使用此代码段时:mContentText.setText(Html.fromHtml(text));,我得到一个带有黑色边框的青色框,这让我相信 TextView 对 img 标签是什么有所了解.

Is it possible to make the image render? When using this snippet: mContentText.setText(Html.fromHtml(text));, I get a cyan box with black borders, leading me to believe that a TextView has some idea of what an img tag is.

推荐答案

如果你看看 Html.fromHtml(text) 的文档你会看到它说:

If you have a look at the documentation for Html.fromHtml(text) you'll see it says:

HTML 中的任何 <img> 标记都将显示为通用替换图像,然后您的程序可以通过它并用真实图像替换.

Any <img> tags in the HTML will display as a generic replacement image which your program can then go through and replace with real images.

如果你不想自己做这个替换,你可以使用 另一个 Html.fromHtml() 方法一个 Html.TagHandler 和一个 Html.ImageGetter 作为参数以及要解析的文本.

If you don't want to do this replacement yourself you can use the other Html.fromHtml() method which takes an Html.TagHandler and an Html.ImageGetter as arguments as well as the text to parse.

在您的情况下,您可以将 null 解析为 Html.TagHandler 但您需要将自己的 Html.ImageGetter 实现为没有默认实现.

In your case you could parse null as for the Html.TagHandler but you'd need to implement your own Html.ImageGetter as there isn't a default implementation.

但是,您将遇到的问题是 Html.ImageGetter 需要同步运行,如果您从 Web 下载图像,您可能希望异步执行该操作.如果您可以在应用程序中添加任何想要显示为资源的图像,那么您的 ImageGetter 实现就会变得简单得多.您可以通过以下方式逃脱:

However, the problem you're going to have is that the Html.ImageGetter needs to run synchronously and if you're downloading images from the web you'll probably want to do that asynchronously. If you can add any images you want to display as resources in your application the your ImageGetter implementation becomes a lot simpler. You could get away with something like:

private class ImageGetter implements Html.ImageGetter {

    public Drawable getDrawable(String source) {
        int id;

        if (source.equals("stack.jpg")) {
            id = R.drawable.stack;
        }
        else if (source.equals("overflow.jpg")) {
            id = R.drawable.overflow;
        }
        else {
            return null;
        }

        Drawable d = getResources().getDrawable(id);
        d.setBounds(0,0,d.getIntrinsicWidth(),d.getIntrinsicHeight());
        return d;
    }
};

不过,您可能想找出更智能的方法来将源字符串映射到资源 ID.

You'd probably want to figure out something smarter for mapping source strings to resource IDs though.

这篇关于是否可以在 Android TextView 中显示来自 html 的内联图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆