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

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.

WebView wv = new WebView(this);
StringBuilder html = new StringBuilder();

html.append("<html>");
html.append("<head>");

html.append("<link rel=stylesheet href='css/style.css'>");
html.append("</head>");
html.append("<body>");
html.append("<h1>Some Heading</h1>");
html.append("<p>Some HTML content</p>");
html.append("<p><img style='width: 100%;' src='spidermen.jpg' /></p>");
html.append("</body></html>");

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