Android WebView Example Tutorial

Android WebView is used to display HTML in an android app. We can use android WebView to load HTML page into android app.

Android WebView

Android WebView component is a full-fledged browser implemented as a View subclass to embed it into our android application.

Importance Of Android WebView

For HTML code that is limited in terms of scope, we can implement the static method fromHtml() that belongs to the HTML Utility class for parsing HTML-formatted string and displaying it in a TextView.

TextView can render simple formatting like styles (bold, italic, etc.), font faces (serif, sans serif, etc.), colors, links, and so forth.

However, when it comes to complex formatting and larger scope in terms of HTML, then TextView fails to handle it well. For example browsing Facebook won’t be possible through a TextView.

In such cases, WebView will be the more appropriate widget, as it can handle a much wider range of HTML tags. WebView can also handle CSS and JavaScript, which Html.fromHtml() would simply ignore.

WebView can also assist with common browsing metaphors, such as history list of visited URLs to support backwards and forwards navigation.

Still WebView comes with its own set of cons such as it’s a much more expensive widget to use, in terms of memory consumption than a TextView. The reason for this increased memory is because WebView is powered by WebKit/Blink that are open source Web rendering engine to power content in browsers like Chrome.

Android WebView Example

Android WebView component is inserted into the XML layout file for the layout we want the WebView to be displayed in. In this example we insert it into the activity_main.xml file as shown below:

Android Studio WebView Code

WebView component is initialized in the MainActivity using its id defined in the activity_main.xml as shown in snippet below:

Android WebView loadUrl

Once we’ve obtained a reference to the WebView we can configure it and load URLs via HTTP. WebView loadUrl() method is used to load the URL into the WebView as shown below:

Before we start toying around with the url there are two critical aspects we should take a look at:

  1. Supporting JavaScript: JavaScript is by default turned off in WebView widgets. Hence web pages containing javascript references won’t work properly. To enable java script the following snippet needs to be called on the webview instance:
  2. Adding Permissions: To fetch and load the urls in the WebView we need to add permissions to access the internet from within the app else it won’t be able to load the webpages. The following line of code needs to be added in the AndroidManifest.xml file above the application tag as shown below:

The MainAcivity class below contains all the features discussed till now.

Setting the WebViewClient

The default behavior when a user clicks on a link inside the webpage is to open the systems default browser app. This can break the user experience of the app users.

To keep page navigation within the WebView and hence within the app, we need to create a subclass of WebViewClient, and override its shouldOverrideUrlLoading(WebView webView, String url) method.

Here is how such a WebViewClient subclass would look:

When the shouldOverrideUrlLoading() method returns false, the URLs passed as parameter to the method is loaded inside the WebView instead of the browser.

To distinguish between the URLs that are loaded within the app and browser the following code needs to be added in the shouldOverrideUrlLoading() method:

Note: Returning true doesn’t signify that the url opens in the browser app. In fact the url won’t be opened at all. To load the url into the browser an intent needs to fired. The following subclass contains all the configurations we’ve added.

The constructor takes Activity as a parameter to fire an intent in the browser.

Before instantiating this subclass in the MainActivity lets look at another important feature.

Navigation WebView with Back Button

If we click the back button in the app developed so far we see that the application returns to the home screen even though we’ve navigated through a few pages within the WebView itself. To go through the browsing history on pressing back button we need to modify the back button function as shown in the snippet below:

The onKeyDown() method has been overridden with an implementation that first checks if the WebView can go back. If the user has navigated away from the first page loaded inside the WebView, then the WebView can go back.

The WebView maintains a browsing history just like a normal browser. If there is no history then it will result in the default behavior of back button i.e. exiting the app.

Following is the code for MainActivity with the above features included.

Below image shows the output produced by our project, you can see that WebView is loaded with a preassigned url.

android webview example

Alternatives for Loading Content in the WebView

Till now we’ve just used loadUrl() method to load the contents in the WebView. Here we’ll see the other ways to load content after a quick briefing of the usages of loadUrl().

loadUrl() works with:

  • https:// and https://URLs
  • file:// URLs pointing to the local filesystem
  • file:///android_asset/ URLs pointing to one of your applications assets
  • content:// URLs pointing to a ContentProvider that is publishing content
    available for streaming

Instead of loadUrl() we can use loadData() by which we can display snippets or whole of the HTML code in the method. There are two flavors of loadData(). The simpler one allows us to provide the content, the MIME type, and the encoding, all as strings. Typically, MIME type will be text/html and the encoding will be UTF-8 for ordinary HTML as shown below:

Below is the output when the above snippet is added in the MainActivity as shown below:

There is also a loadDataWithBaseURL() method. This takes, among other parameters, the base URL to use when resolving relative URLs in the HTML. Any relative URL (e.g., <img src=”images/sample.png”>) will be interpreted as being relative to the base URL supplied to loadDataWithBaseURL().

The historyUrl parameter is the URL to write into the WebView internal navigation history for the HTML loaded into the WebView. The following snippet shows a prototype for it:

This brings an end to android WebView example tutorial. You can download final android webview project from below link.

By admin

Leave a Reply