Using WebView to display HTML in Android Xamarin Apps

Using Web View

Often in our apps we want to be able to deliver web content that we already have or maybe just a web page as part of the client application. This is helpful especailly if we already have this content available as HTML and we don’t want to have to re-create it in our app format or create new views. Xamarin makes this easy with the WebView class. WebView allows you to create your own window for viewing web pages (or even develop a complete browser).

A common scenario in which using WebView is helpful is when you want to provide information in your application that you might need to update, such as an end-user agreement or a user guide. Within your Android application, you can create an Activity that contains a WebView, then use that to display your document that’s hosted online.

Using WebView in your application is very easy. It requires the Android.Webkit library to be added in and then with a few lines of code you can be up and running!

myWebView = FindViewById<WebView>(Resource.Id.webView1);
 myWebView.SetWebViewClient(new WebViewClient());
 myWebView.Settings.JavaScriptEnabled = true;

Enabling JavaScript on WebView

If the web page you plan to load in your WebView use JavaScript, you must enable JavaScript for your WebView. Once JavaScript is enabled, you can also create interfaces between your application code and your JavaScript code. JavaScript is disabled in a WebView by default.


Handling Page Navigation

One of the trickiest parts of using WebView is being able to manage the page navigation. When the user clicks a link from a web page in your WebView, the default behavior is for Android to launch an application that handles URLs. Usually, the default web browser opens and loads the destination URL. This is obviously not what we want to have happen. WebView does keep track of page navigation history so we can allow the user to move backwards and forwards while still retaining them in the WebView frame of our app and not opening the browser.

Ultimately we can control this by overriding the OnBackPressed method and using the WebView’s history instead. When your WebView overrides URL loading, it automatically accumulates a history of visited web pages. You can navigate backward and forward through the history with GoBack() and GoForward().

public override void OnBackPressed()

Loading Local Content

Sometimes we have HTML pages that we want to load in but they aren’t necessarily hosted URLs.  We can use the same concepts to load in local HTML pages in a Web View.  This can be helpful if you already have the HTML content (like the end-user agreement example from the start) and want to render it out to your user as-is.

For a complete walk-through of these concepts check out my video below.  You can also get a complete download of the project on my Github.

Leave a Reply

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