Android: Display local image/CSS files in HTML with WebView

0 Comments

Displaying custom HTML in a WebView is pretty easy, as explained in a post I made long ago in 2009.

However, if you want to spruce it up with some images and CSS, you'll have to tweak it a little. Don't worry, it's not hard at all!

Here is an example that's a bit more verbose.

01.WebView wv = new WebView(this);
02.StringBuilder html = new StringBuilder();
03. 
04.html.append("<html>");
05.html.append("<head>");
06. 
07.html.append("<link rel=stylesheet href='css/style.css'>");
08.html.append("</head>");
09.html.append("<body>");
10.html.append("<h1>Some Heading</h1>");
11.html.append("<p>Some HTML content</p>");
12.html.append("<p><img style='width: 100%;' src='spidermen.jpg' /></p>");
13.html.append("</body></html>");
14. 
15.wv.loadDataWithBaseURL("file:///android_asset/", html.toString(), "text/html", "UTF-8", "");

Now you'll be able to see that it has links to "css/style.css" and "spidermen.jpg". This files will be included as part of your application, not hosted on the web somewhere.

To access them, you can specify a full path "file:///android_asset/spidermen.jpg" or set the baseURL for the WebView to be "file:///android_asset/".

Now to put the files in the right place.

image

And that's pretty much it!

Running it in the emulator will show you THIS!

image

Source: WebView with custom HTML and local images

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog