Android: How to reference asset images from a remotely loaded html page in webview

后端 未结 2 685
刺人心
刺人心 2020-12-09 06:13

I\'m trying to load/reference images from the app\'s assets folder from within a HTML page in a WebView. Unlike in most of the examples the HTML page itself is not located i

相关标签:
2条回答
  • 2020-12-09 06:16

    OK, thanks to mufumbo's answer I now found a working hack to mix local assets in remotely loaded HTML pages. Pages loaded using the WebView's loadUrl() method do not load images linked with file:///android_asset/... As a workaround you can fetch the HTML page using org.apache.http.client.methods.HttpGet.HttpGet() and then pass it to the WebView with loadDataWithBaseURL(). In this case the WebView will load resources linked with file:///android_asset/ as well as images and scripts via HTTP. Here's my customized webview code:

    public class CustomWebView extends WebView {
        private String mURL;
    
        public void loadUrlWithAssets(final String url) {
            // copy url to member to allow inner classes accessing it
            mURL = url;
    
            new Thread(new Runnable() {
                public void run() {
                    String html;
                    try {
                        html = NetUtil.httpGETResponse(mURL);
    
                        // replace some file paths in html with file:///android_asset/...
    
                        loadDataWithBaseURL(mURL, html, "text/html", "UTF-8", "");
                    }
                    catch (IOException e) {
                        Log.e("CustomWebView.loadUrlWithAssets", "IOException", e);
                    }
                }
            }).start();
        }
    }
    

    Please note that the whole http fetching is wrapped in the home-grown utility class NetUtil.

    With this class it's possible to render HTML pages from a webserver and have some static resources like images or stylesheets loaded from the app's asset folder in order to improve loading speed and to save bandwidth.

    0 讨论(0)
  • 2020-12-09 06:19

    This is how I do on the java part:

    String myHTML = "< img src=\"file:///android_asset/myimage.jpg\""; myWebView.loadDataWithBaseURL("file:///android_asset/", myHTML, "text/html", "UTF-8", "");

    cheers

    0 讨论(0)
提交回复
热议问题