DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How To Optimize and Reduce Android Apps Size in Xamarin
  • Issue and Present Verifiable Credentials With Spring Boot and Android
  • How to Build a React Native Chat App for Android
  • Using Jetpack Compose With MVI Architecture

Trending

  • Optimizing Integration Workflows With Spark Structured Streaming and Cloud Services
  • How to Practice TDD With Kotlin
  • Cosmos DB Disaster Recovery: Multi-Region Write Pitfalls and How to Evade Them
  • Mastering Fluent Bit: Installing and Configuring Fluent Bit on Kubernetes (Part 3)
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Deployment
  4. WebView in Xamarin Android

WebView in Xamarin Android

If you want to display HTML content or web content on your app, look to Xamarin. You can load static HTML, open web pages and URLs, and work easily with navigation.

By 
Anoop Kumar Sharma user avatar
Anoop Kumar Sharma
DZone Core CORE ·
Feb. 17, 17 · Tutorial
Likes (0)
Comment
Save
Tweet
Share
25.1K Views

Join the DZone community and get the full member experience.

Join For Free

In this article, we will learn how to use WebView in Xamarin. WebView is used for displaying HTML content or web content in your app. Let's begin!

Load Static HTML in WebView

For this example, you'll need to create a new Xamarin Android project. Click on the blank Android app, give it a meaningful name, and then click OK.

Image title

Add a WebView in LinearLayout (Vertical):

Image title

Main XML Code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:minWidth="25px"
    android:minHeight="25px">
    <android.webkit.WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/webView" />
</LinearLayout>

Open MainActivity.cs. Get WebView control/view from the Main Layout and Load HTML data in WebView using the below code.

MainActivity.cs:

using Android.App;
using Android.Widget;
using Android.OS;
using Android.Webkit;

namespace WebViewHTMLPage {
 [Activity(Label = "WebViewHTMLPage", MainLauncher = true, Icon = "@drawable/icon", Theme = "@android:style/Theme.NoTitleBar")]
 public class MainActivity: Activity {
  //Creating Instance of Webview
  WebView webView;
  protected override void OnCreate(Bundle bundle) {
   base.OnCreate(bundle);

   // Set our view from the "main" layout resource
   SetContentView(Resource.Layout.Main);
   //Get webView WebView from Main Layout
   webView = FindViewById < WebView > (Resource.Id.webView);
   //HTML String
   string HTMLText = "<html>" + "<body>Sample <b>HTML</b> Text<br/><br/>" +
    "<span style='color:red;'>Application created by: Anoop Kumar Sharma<span></body>" +
    "</html>";
   //Load HTML Data in WebView
   webView.LoadData(HTMLText, "text/html", null);
  }
 }
}

Build and run the application:

Image title

Open Web Page or URL in WebView 

For this example, let’s add LinearLayout (Horizontal) and WebView controls in LinearLayout (Vertical) on the Main Layout. Add a "plain text" and "button" widget in the horizontal layout, as shown in the image below.

Image title

When a user types a URL or website name in plain text view and presses Go, we will open a webpage in the WebView widget.

Main XML code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/linearLayout1">
        <EditText
            android:layout_height="match_parent"
            android:id="@+id/txtURL"
            android:layout_weight="1"
            android:layout_width="match_parent"
            android:hint="www.google.com" />
        <Button
            android:text="Go"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:id="@+id/btnGo" />
    </LinearLayout>
    <android.webkit.WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/webView" />
</LinearLayout>

MainActivity.cs code:

using Android.App;
using Android.Widget;
using Android.OS;
using Android.Webkit;

namespace WebViewinXamarin {
 [Activity(Label = "WebViewinXamarin", MainLauncher = true, Icon = "@drawable/icon", Theme = "@android:style/Theme.NoTitleBar")]
 public class MainActivity: Activity {
  //Creating Instance of Button,TextView, WebView
  Button btnGo;
  TextView txtURL;
  WebView webView;
  protected override void OnCreate(Bundle bundle) {
   base.OnCreate(bundle);

   // Set our view from the "main" layout resource
   SetContentView(Resource.Layout.Main);
   //Get txtURL TextView, btnGo Button,webView WebView from Main Resource Layout.
   txtURL = FindViewById < TextView > (Resource.Id.txtURL);
   btnGo = FindViewById < Button > (Resource.Id.btnGo);
   webView = FindViewById < WebView > (Resource.Id.webView);

   //SetWebViewClient with an instance of WebViewClientClass
   webView.SetWebViewClient(new WebViewClientClass());
   webView.LoadUrl(txtURL.Text);

   //Enabled Javascript in Websettings
   WebSettings websettings = webView.Settings;
   websettings.JavaScriptEnabled = true;

   //btnGo Click event
   btnGo.Click += BtnGo_Click;
  }

  private void BtnGo_Click(object sender, System.EventArgs e) {
   //Load URL in txtURL in WebView.
   webView.LoadUrl(txtURL.Text);
  }
 }

 internal class WebViewClientClass: WebViewClient {
  //Give the host application a chance to take over the control when a new url is about to be loaded in the current WebView.
  public override bool ShouldOverrideUrlLoading(WebView view, string url) {
   view.LoadUrl(url);
   return true;
  }
 }
}

Build and run the application:

Image title

Working With Navigation in WebView

WebView has several methods and properties that support navigation like GoForward(), GoBack(), CanGoBack, and CanGoForward. In this example, we will add Back and Forward buttons in the Main.xml layout.

Main XML code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/txtURL" />
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/linearLayout1">
        <Button
            android:text="Back"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:id="@+id/btnBack"
            android:layout_weight="1" />
        <Button
            android:text="Go"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:id="@+id/btnGO"
            android:layout_weight="2" />
        <Button
            android:text="Forward"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:id="@+id/btnForward"
            android:layout_weight="1" />
    </LinearLayout>
    <android.webkit.WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/webView" />
</LinearLayout>

MainActivity.cs:

using Android.App;
using Android.Widget;
using Android.OS;
using Android.Webkit;
using Android.Runtime;
using Android.Views;

namespace WebViewwithNavigation {
 [Activity(Label = "WebViewwithNavigation", MainLauncher = true, Icon = "@drawable/icon", Theme = "@android:style/Theme.NoTitleBar")]
 public class MainActivity: Activity {
  Button btnBack;
  Button btnGo;
  Button btnForward;
  TextView txtURL;
  WebView webView;
  protected override void OnCreate(Bundle bundle) {
   base.OnCreate(bundle);

   // Set our view from the "main" layout resource
   SetContentView(Resource.Layout.Main);

   btnGo = FindViewById < Button > (Resource.Id.btnGO);
   btnBack = FindViewById < Button > (Resource.Id.btnBack);
   btnForward = FindViewById < Button > (Resource.Id.btnForward);
   txtURL = FindViewById < TextView > (Resource.Id.txtURL);
   webView = FindViewById < WebView > (Resource.Id.webView);

   webView.SetWebViewClient(new WebViewClientClass());

   WebSettings websettings = webView.Settings;
   websettings.JavaScriptEnabled = true;

   btnGo.Click += BtnGo_Click;
   btnBack.Click += BtnBack_Click;
   btnForward.Click += BtnForward_Click;
  }

  private void BtnForward_Click(object sender, System.EventArgs e) {
   //If WebView has forward History item then forward to the next visited page.
   if (webView.CanGoForward()) {
    webView.GoForward();
   }
  }

  private void BtnBack_Click(object sender, System.EventArgs e) {
   //If WebView has back History item then navigate to the last visited page.
   if (webView.CanGoBack()) {
    webView.GoBack();
   }
  }

  private void BtnGo_Click(object sender, System.EventArgs e) {
   webView.LoadUrl(txtURL.Text);
  }
 }

 internal class WebViewClientClass: WebViewClient {
  public override bool ShouldOverrideUrlLoading(WebView view, string url) {
   view.LoadUrl(url);
   return true;
  }
 }
}

Build and run the application. Go to any web URL (in my case, I am visiting Google).

Image title

After that, I searched "c-sharp corner" in Google and clicked on its official site in order to generate the back history items.

Image title


After the URL opens, click the back and forward button in order to navigate from one page to another.

Image title


Hope you like this! Thanks for reading.

xamarin Android (robot)

Published at DZone with permission of Anoop Kumar Sharma, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How To Optimize and Reduce Android Apps Size in Xamarin
  • Issue and Present Verifiable Credentials With Spring Boot and Android
  • How to Build a React Native Chat App for Android
  • Using Jetpack Compose With MVI Architecture

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!