【问题标题】:Is it possible to display image with loadDataWithBaseURL() method in android?是否可以在 android 中使用 loadDataWithBaseURL() 方法显示图像?
【发布时间】:2011-03-05 10:21:40
【问题描述】:

我正在尝试使用 android 中的loadDataWithBaseURL() 方法显示 html 文件的内容。

我只有一个字符串,其中包含一个名为 source 的字符串中的 Html 文件数据,然后我将它传递给方法。

例如

String source; //contain html tags with images
View.loadDataWithBaseURl(null,source,"text/html","UTF-8","about:blank");

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

【问题讨论】:

  • 您发布的代码将不起作用,因为 source 将为空,并且 View.load 只有在您有一个以大写字母开头的 View 对象时才能工作。但是您说视图很好,因此我认为这只是示例代码。

标签: html android image webview


【解决方案1】:

您可以这样做,如果源中的图像使用 src 的相对位置,那么您需要将 baseUrl 设置为图像所在位置的“基础”。例如,如果您从源代码加载 google 的主页,它将如下所示:

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

这告诉 webview 将从哪里加载图像。

附带说明,出于安全原因,我认为“file://”URI 不能在 Web 视图中使用。

【讨论】:

  • 我使用文件 URI 将图像从内部存储器加载到 webview 中,它工作正常
【解决方案2】:

使用“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);

【讨论】:

    【解决方案3】:

    我已经制作了一个关于如何使用 loadDataWithBaseURL() 方法来显示图像的教程 - http://lomza.totem-soft.com/tutorial-using-webview-to-load-the-html-page-from-assets/#header

    【讨论】:

      【解决方案4】:

      例如,如果您想使用 sdcard 中的一些图像,那么您的代码应该是这样的:

      final String path = Environment.getExternalStorageDirectory() + File.separator + "YourFolderName"); bookView.loadDataWithBaseURL("file://" + path, htmlTextWithHeadAndBody, "text/html", "UTF-8", "");

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-21
        • 2013-11-16
        相关资源
        最近更新 更多