在安卓中使用loadDataWithBaseURL()方法能否显示图片?

6
我将尝试使用android中的loadDataWithBaseURL()方法来显示一个html文件的内容。
我只有一个包含html文件数据的字符串,名为source,然后将其传递给该方法。
例如:
String source; //contain html tags with images
View.loadDataWithBaseURl(null,source,"text/html","UTF-8","about:blank");

视图中显示的数据很好。 我的问题是,如果我的HTML文件包含任何图片,那么我无法显示它? 我该怎么办?


1
你发布的代码无法工作,因为源将为空,并且View.load只能在以大写字母开头的View对象存在时才能工作。但是你说视图很好,因此我假设这只是示例代码。 - Janusz
3个回答

5

如果源文件中的图像使用相对位置的src,那么您需要将baseUrl设置为图像所在位置的“基础”位置。例如,如果您正在从源加载谷歌主页,则应该如下所示:

View.loadDataWithBaseURI("http://google.com",source,"text/html","UTF-8","about:blank");

那会告诉Webview从哪里加载图片。 顺便提一下,出于安全原因,我认为在Webview中不支持“file://” URI。

1
我使用文件URI从内部存储加载图片到Webview,效果良好。 - Janusz

3
请使用"file:///android_res/raw/"作为您的基础URL,并将文件放置在项目中的res/raw目录下。 res/raw/index.html res/raw/image.jpg
InputStream htmlStream = getResources().openRawResource(R.raw.index);
Reader is = new BufferedReader(new InputStreamReader(htmlStream, "UTF8"));

// read string from reader
String html = readFile(is);

webView.loadDataWithBaseURL("file:///android_res/raw/", html, 
                            "text/html", "UTF-8", null);

1
例如,如果您想要从SD卡中使用一些图像,则您的代码应该像这样:
final String path = Environment.getExternalStorageDirectory() + File.separator + "YourFolderName"); bookView.loadDataWithBaseURL("file://" + path, htmlTextWithHeadAndBody, "text/html", "UTF-8", "");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接