Adding formatted HTML text to your Android app

HelpTextRender

To help make our Android applications look even more professional, we can include HTML formatted text and display it in a WebView. Here’s the simplest way I’ve found to have local HTML, image and style files and display them. This is the same process I use to display help in Grandma Jong.

First, I’ve stored all my files in a subfolder of assets. This will make it easier to load the HTML, and via some built-in functionality in Android, it will load all assets from the same folder as well. Here’s a screenshot of the assets folder:

AssetsFolder

Here I have the HTML file, along with the referenced images. Now a glance into what the HTML looks like:

<p>
<img src=”bomb.png” align=”left” style=”margin-right:1em;” /> Don’t despair! Bomb tiles let you clear blocked tiles; just select the tile to remove, then select a bomb tile on the left. A matching tile will be removed from the level.
</p>

The <img> tag just has a straightforward reference to the image file, since when loading the HTML, the passed in path will be taken as the root path and all references are valid from there. Finally, there’s the WebView code needed to load the HTML from the assets folder. Once you have a reference to a WebView instance, all you need to do is call the loadUrl method on it:

webViewInstance.loadUrl(“file:///android_asset/help/help.html”);

The “file:///android_asset” path is a special one that points to the assets folder in your project. That’s all there is to it. Although I haven’t demonstrated it here, you can also store and load style and javascript files the same way.

Leave a Reply

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