11

在我的项目中,我有一个文件:

"MyProject/assets/folder1/image1.jpg"
"MyProject/assets/folder1/index.html".

在 webView 我需要打开 index.html (带图像)。

我尝试这段代码:

String baseUrl = "file:///android_asset/folder1/";
webView.loadDataWithBaseURL(baseUrl, readFileAsString("index.html") , mimeType, "UTF-8", null);

但图像不加载。

如果我将图像放入“资产”目录(MyProject/assets/)并baseUrl = "file:///android_asset"正确加载图像;

如何不仅从根资产目录加载图像,而且从assets/folder1?

4

4 回答 4

15

试试这样

WebView webview = (WebView)this.findViewById(R.id.webview);


String html = "<html><head><title>TITLE!!!</title></head>";
html += "<body><h1>Image?</h1><img src=\"icon.png\" /></body></html>";


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

有关更多信息,请尝试此链接

完美的LoadDataWithBaseurl

于 2013-01-17T08:29:59.490 回答
5

我认为您必须将基础设置为资产并将子文件夹添加到您的图像 src,如下所示:

webView.loadDataWithBaseURL("file:///android_asset/", readAssetFileAsString("folder1/index.html"), "text/html", "UTF-8", null);

html: <img src="folder1/image1.jpg">

这在 Android 5.1 上对我有用

private String readAssetFileAsString(String sourceHtmlLocation)
{
    InputStream is;
    try
    {
        is = getContext().getAssets().open(sourceHtmlLocation);
        int size = is.available();

        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();

        return new String(buffer, "UTF-8");
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }

    return "";
}
于 2016-07-28T01:45:12.997 回答
1

试着喜欢这个

try {
            String filePath = null;
            filePath = "Your File path";
            Bitmap bitmap = null;

            bitmap = BitmapFactory.decodeFile(filePath);
            Log.v("Image data-->", "" + bitmap);
            imageWidth = bitmap.getWidth();
            imageHeight = bitmap.getHeight();
            Log.e("Width", "" + imageWidth);
            filePath = "file://" + filePath;
            String html = "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv=\"Content-Type\" content=\"text/html\";charset=utf-8\"/><title></title></head><body style=\"width:"
                    + imageWidth
                    + "px; height:"
                    + imageHeight
                    + "px; background:url("
                    + filePath
                    + ") no-repeat; position:relative;\">"
                    + getDivTag(mapList)
                    + "</body></html>";

            Log.v("MIS", "" + html);
            webview.getSettings().setSupportZoom(true);
            webview.loadDataWithBaseURL(null, html, "text/html", "utf-8", null);

            System.out.println(html);

        } catch (Exception e) {
            e.printStackTrace();
        }
于 2013-01-17T10:37:13.903 回答
-15

你有上网权限吗?

<uses-permission android:name="android.permission.INTERNET" />
于 2013-01-17T08:08:25.570 回答