Showing static HTML in WebView – Android

Loading a live web page from the internet into Webview object is straight forward.
The simplest way is to create a Webview object and load URL into the object:

But what if you need to show a custom HTML page to your users?

For a simple static page you can create a HTML document in a string variable and load it into Webview object:

This is cool but what if you need to have a more complex HTML page with CSS blocks?
In that case you need to have a HTML file and store it in your project asset folder.
You need to use ‘loadDataWithBaseURL()’ method instead to provide webView with asset folder as base URL (where data is content of HTML file) :

You can read content of HTML file from asset folder and save it into a String variable (data) and pass it to loadDataWithBaseURL method.
Below method is just one way of reading a file content into a variable:

Leave a Reply

Your email address will not be published. Required fields are marked *