How to load local image in Android WebView

前端 未结 4 1940
情书的邮戳
情书的邮戳 2021-01-05 08:56

I\'m trying to load a html string stored in the database which contain a image into a WebView. The image is stored in the internal memory. I am giving a referen

4条回答
  •  耶瑟儿~
    2021-01-05 09:09

    In latest android versions we cant access resources such as assets , files from storage. https://developer.android.com/reference/androidx/webkit/WebViewAssetLoader is best guide to proceed. WebViewAssetLoader and its internal classes helps to access them.

    you can check the below sample code.

        final WebViewAssetLoader assetLoader = new WebViewAssetLoader.Builder()
                .addPathHandler("/assets/", new WebViewAssetLoader.AssetsPathHandler(this)) //****for assets****
                .addPathHandler("/images/", new WebViewAssetLoader.InternalStoragePathHandler(context, getFilesDir()))//****for files****
                .build();
    
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view,
                                                              WebResourceRequest request) {
                return assetLoader.shouldInterceptRequest(request.getUrl());
            }
        });
    
        String assetsPic = "";
        String storagePic = "";
        webView.loadData(assetsPic+"
    "+storagePic, "text/html", "UTF-8");

提交回复
热议问题