Android webview loadDataWithBaseURL how load images from assets?

前端 未结 4 1483
花落未央
花落未央 2020-12-03 05:41

In my project I have a files:

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

In webView I need to open i

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-03 06:24

    I think you have to set the base to assets and add the sub folders to your image src's like this:

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

    Html:

    This worked for me on 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 "";
    }
    

提交回复
热议问题