How to Display HTML Content in Android

To display HTML content or browse a website in Android you need to use WebView widget which is packaged in Android WebKit. Depending on your application, you can develop a very powerful app with impressing functionality.

Here’s a simple example on how you can use WebView in your Android application. First, lets create an XML layout that will include a WebView widget.

 

Now we have our XML layout file with WebView widget. Before we jump into the Java code, we need to know how to display HTML content. There are two ways we can get HTML content into WebView.

  • loadUrl() – takes a web address as a string or a file in the assets folder. Also make sure you add access internet permission in manifest file.
  • loadData() – takes MIME type and the encoding. This will be your text/html file  and the encoding will be the UTF-8 for HTML.

Here is the code that elaborate both ways:

As I mentioned above, remember to add access internet permission in your manifest file to be able to open the website provided in loadUrl() method.

Note, if this was a real application, you will have to decide what method to use or create options with if or case statement otherwise this will not work. Read more from chapter 13 on Beginning Android 2 by Mark Murphy. It is a very easy book to read with full details on how to make a fully functional app using Android WebKit package.

Hope this helps and will give you the answer you were looking for. Good luck!

 

You may also like...