Вопрос

I want to load the following HTML code in the Android webview.

<!DOCTYPE html>
<html>
<body style = "text-align:center">

<img src="http://XXXXXXXX.com/books_snaps/UR335/1.jpg" alt="pageNo" 

height="100%" width="100%"> 

</body>
</html>

where http://XXXXXXXX.com/books_snaps/UR335/1.jpg is a image link. I want to load this image in <img> tag of above HTML. How can I embed above HTML code in webview of Android?

Это было полезно?

Решение

String htmlString = "<!DOCTYPE html><html><body style = \"text-align:center\"><img src=\"http://shiaislamicbooks.com/books_snaps/UR335/1.jpg\" alt=\"pageNo\" height=\"100%\" width=\"100%\"></body></html>";
webview.loadDataWithBaseURL(null,htmlString,"text/html","UTF-8","about:blank");

Also, you need to add the internet permission,

<uses-permission android:name="android.permission.INTERNET" /> 

Другие советы

you can first save the html file in assets folder say

assets\html\index.html

then just load the Page to webview as

   webView.loadUrl("file:///android_asset/html/index.html");

or you can try this

String content = 
       "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"+
       "<html><head>"+
       "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />"+
       "<head><body>";

content += myContent + "</body></html>";

WebView WebView1 = (WebView) findViewById(R.id.webView1);
WebView1.loadData(content, "text/html; charset=utf-8", "UTF-8");

Following Sanket Kachhela answer, if you run your app on Android 9.0 device, and still don't see the images, consider adding android:usesCleartextTraffic="true" to Application tag in the Manifest file.

 <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    android:usesCleartextTraffic="true">
    ...

For me it did the job.

See this thread

You can download that image from the link and then you need to create a folder named "Images" into your android application assests folder.

And then after you can change the path of your image link to ../images/1.jpg in your html file.

Try out this way. I am sure it will work.

Thanks.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top