showing image from sdcard with webview not working

2020-07-17 08:12发布

I have downloaded map750.png file in the root of sdcard, but when I try to show it within a webview with some text, only the text is shown. Could you help me to find what is wrong in the code? thanks.

setContentView(R.layout.webview);
    mWebView = (WebView) findViewById(R.id.webview);
    mWebView.getSettings().setAllowFileAccess(true);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setBuiltInZoomControls(true);
    String html = "<html><head></head><body><p>hello</p><img src=\"file://mnt/sdcard/map750.png\" alt=\"alternativo\" /></body></html>";
    mWebView.loadData(html, "text/html","utf-8");

I edit the post to add the solution suggested by oneilse14, thanks!!

setContentView(R.layout.webview);
    mWebView = (WebView) findViewById(R.id.webview);
    mWebView.getSettings().setAllowFileAccess(true);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setBuiltInZoomControls(true);
    String html = "<html><head></head><body><p>hello</p><img src=\"file://mnt/sdcard/map750.png\" alt=\"alternativo\" /></body></html>";
    mWebView.loadDataWithBaseURL("", html, "text/html", "utf-8", "");

3条回答
老娘就宠你
2楼-- · 2020-07-17 08:46

Try this,

        final String fileName = "file:///mnt/sdcard/1.jpg";
        final String mimeType = "text/html";
        final String encoding = "utf-8";
        final String html = "<img src=\""+fileName+"\">";
        webView.loadDataWithBaseURL("", html, mimeType, encoding, "");
查看更多
孤傲高冷的网名
3楼-- · 2020-07-17 08:49

Check out loadDataWithBaseURL() in the Developer docs

http://developer.android.com/reference/android/webkit/WebView.html

loadData() has certain restrictions on what it can display. This method is able to display local device files like you are trying to do.

查看更多
我欲成王,谁敢阻挡
4楼-- · 2020-07-17 08:53

Note that the access using the file:// schema can fail due security restrictions.

Another approach is to use the URI of a ContentProvider that handles the local file access. Overwrite openFile(Uri, String) in a subclass of ContentProvider for this approach.

查看更多
登录 后发表回答