Although the layout and control options within the Xamarin flavour of XAML are pretty extensive, you may come across the need to quickly display some HTML formatted content.  Maybe your CMS has some HTML content that it just doesn’t make sense to invest time into changing, or your app needs to display a web page.

Whatever the use-case, you do have some options.

In this first part, we will take a look at the simplest option, the WebView control.

The WebView

The WebView control is an out of the box Xamarin Forms component that you can get started with in less than a minute.

Let’s start with a blank Forms PCL project. Open the new MainPage.xaml and remove the sample Label control.  We’ll replace it with a three row Grid (using * notation to set the row heights to equal sizes), and a WebView in Grid.Row 0.

<Grid>

    <Grid.RowDefinitions>
        <RowDefinition Height="1*" />
        <RowDefinition Height="1*" />
        <RowDefinition Height="1*" />
    </Grid.RowDefinitions>

    <WebView Grid.Row="0"
Source="http://www.xamarin.com" />
</Grid>

Run the project and you should see your main page, with Xamarin.com in the top row. We’ll use the other grid rows later on, to demonstrate a different view source and a custom HTML label.

HTML0

It’s worth noting that if the WebView is contained in a StackLayout or RelativeLayout, it will not render unless you specifiy a HeightRequest and WidthRequest.

Other sources

WebView can also display HTML from other sources, such as a simple string, or content embedded in your app.

To display a string of HTML programatically, set the source of the WebView to a new HtmlWebViewSource:

public MainPage()
{
     InitializeComponent();

     MyWebView.Source = new HtmlWebViewSource
     {
         Html = @"<html><body>An html string</body></html>"
     };
}

 HTML2.PNG

Events

The WebView raises two events, Navigating and Navigated, when navigation begins and ends respectively. These are particularly useful for adding a loading indicator – web content can take a while to load.

Permissions

WebView requires no special permissions on iOS.  On Android, however, the INTERNET permission is required to display anything other than locally embedded HTML.

Check out the developer documentation to learn more about the WebView.

Any other options?

In Part 2 of this post, we’ll take a look at using the platform specific support for HTML, and write our own custom Label using a custom renderer.

 

 

Advertisement