是否有可能在Android TextView中显示内嵌图像的HTML?有可能、内嵌、图像、TextView

2023-09-12 21:35:54 作者:梦里梦到醒不来的梦

由于下面的HTML:

&LT; P&gt;这是文字,这是一个图像&LT; IMG SRC =htt​​p://www.example.com/image.jpg/>.</p>

是否有可能使图像呈现?当使用这个片断: mContentText.setText(Html.fromHtml(文本)); ,我与黑色边框青色盒,导致我相信,一个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.

推荐答案

如果你有看documentation为 Html.fromHtml(文字) 你会看到它说:

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

任何&LT; IMG&GT; 标签中的HTML将显示为一个通用的替换图像,你的程序就可以通过更换和真实图像

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.

如果你不想自己做这种替换,您可以使用the其他 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.

在你的情况,你可以解析作为 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 需要同步运行,如果你从网上下载的图片,你可能会要做到这一点异步的。如果你可以添加你想要显示的资源在应用程序中的任何图像的 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.