是否可以在Android TextView中显示来自html的嵌入式图像?

鉴于以下HTML:


<p>This is text and this is an image <img src="http://www.example.com/image.jpg" />.</p>


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


FFIVE
浏览 727回答 3
3回答

倚天杖

如果您查看文档,Html.fromHtml(text)它会显示:<img>HTML中的任何标签都将显示为通用替换图像,您的程序可以通过该替换图像进行浏览,并用实际图像替换。如果您不想自己进行替换,则可以使用另一个Html.fromHtml()方法,该方法采用an Html.TagHandler和Html.ImageGetteras参数以及要解析的文本。在您的情况下,您可以将解析null为,Html.TagHandler但Html.ImageGetter由于没有默认实现,因此您需要自己实现。但是,您将要面临的问题是Html.ImageGetter需要同步运行,如果要从Web下载图像,则可能需要异步执行。如果可以在应用程序中添加要显示为资源的任何图像,则ImageGetter实现将变得更加简单。您可以通过以下方式摆脱困境:private class ImageGetter implements Html.ImageGetter {&nbsp; &nbsp; public Drawable getDrawable(String source) {&nbsp; &nbsp; &nbsp; &nbsp; int id;&nbsp; &nbsp; &nbsp; &nbsp; if (source.equals("stack.jpg")) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; id = R.drawable.stack;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else if (source.equals("overflow.jpg")) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; id = R.drawable.overflow;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; Drawable d = getResources().getDrawable(id);&nbsp; &nbsp; &nbsp; &nbsp; d.setBounds(0,0,d.getIntrinsicWidth(),d.getIntrinsicHeight());&nbsp; &nbsp; &nbsp; &nbsp; return d;&nbsp; &nbsp; }};不过,您可能想找出一些更聪明的方法,用于将源字符串映射到资源ID。

呼唤远方

这就是我使用的方法,不需要您对资源名称进行硬核化,并且会在没有找到任何内容的情况下先在您的应用程序资源中查找可绘制资源,然后在库存的android资源中查找可绘制资源-允许您使用默认图标等。private class ImageGetter implements Html.ImageGetter {&nbsp; &nbsp; &nbsp;public Drawable getDrawable(String source) {&nbsp; &nbsp; &nbsp; &nbsp; int id;&nbsp; &nbsp; &nbsp; &nbsp; id = getResources().getIdentifier(source, "drawable", getPackageName());&nbsp; &nbsp; &nbsp; &nbsp; if (id == 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // the drawable resource wasn't found in our package, maybe it is a stock android drawable?&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; id = getResources().getIdentifier(source, "drawable", "android");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (id == 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // prevent a crash if the resource still can't be found&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Drawable d = getResources().getDrawable(id);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; d.setBounds(0,0,d.getIntrinsicWidth(),d.getIntrinsicHeight());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return d;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp;}&nbsp;}可以这样使用(示例):String myHtml = "This will display an image to the right <img src='ic_menu_more' />";myTextview.setText(Html.fromHtml(myHtml, new ImageGetter(), null);
打开App,查看更多内容
随时随地看视频慕课网APP