Android WebView Tutorial With Example

Hello Readers! In this post, we are going to learn about how to use android WebView widget in any android application. We will also go through different attributes of WebView widget that can be used to customise it. We will learn how to use webChromeClient, WebViewClient or WebSettings to customise it. We will see how to load data into android webView from different sources. For example, data from local file, from any given url etc.

Output

Tutorialwing Android WebView Output Android WebView Tutorial With Example

Tutorialwing Android WebView Output

Getting Started

WebView widget can be defined as below –

WebView is a view that displays webpage. This class is used to implement own web browser or simply display the online content in an activity.

WebView uses webkit rendering engine to –
   – Display webpages
   – Includes methods to navigate forward and backward through history.
   – Zoom in zoom out
   – Text Searches and many more things

Attributes of Android WebView Widget

Some of the popular attributes of android webView widget inherited from ViewGroup are –

Sr. XML Attributes Description
1 android:clipChildren Defines whether a child is limited to draw inside of its bounds or not
2 android:layoutAnimation Defines the layout animation to use when the viewGroup is laid out for the first time
3 android:persistentDrawingCache Defines the persistent of the drawing cache
4 android:layoutMode Defines layout mode this viewGroup

Some of the popular attributes of android WebView inherited from View are –

Sr. XML Attributes Description
1 android:alpha Defines alpha of the view
2 android:background Defines drawable to be used for the background
3 android:contextClickable Defines whether this view should react to context click event
4 android:elevation Defines base z depth of the view
5 android:fitsSystemWindows It is used to adjust view layout based on system windows such as status bar etc. It accepts true or false value.
6 android:foreground Defines the drawable to draw over the content
7 android:foregroundGravity Defines the gravity of the foreground drawable



Example of Android WebView Widget

At first, we will create android application. Then, we will use WebView widget in this application.

1. Creating New Project

Follow steps below to create new project. Please ignore the steps if you have already created a new application.

Step Description
1. Open Android Studio.
2. Go to File => New => New Project. Write application name as WebView. Then, click next button.
3. Select minimum SDK you need. However, we have selected 17 as minimum SDK. Then, click next button
4. Then, select Empty Activity => click next => click finish.
5. If you have followed above process correctly, you will get a newly created project successfully. However, you can also visit post to create a new project to know steps in detail.

Now, we will modify xml and java file to use WebView widget in the application.

2. Modify Values folder

Open res/values/strings.xml file. Then, add below code into it.

<resources>
	<string name="app_name">WebView</string>
	<string name="site_url">https://tutorialwing.com</string>
</resources>

Open res/values/styles.xml file. Then, add below code into it.

<resources>

	<!-- Base application theme. -->
	<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
		<!-- Customize your theme here. -->
		<item name="colorPrimary">@color/colorPrimary</item>
		<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
		<item name="colorAccent">@color/colorAccent</item>
	</style>

</resources>

We are not showing toolBar in the application. So, we have changed the parent theme to Theme.AppCompat.Light.NoActionBar.

Open res/values/colors.xml file. Then, add below code into it.

<?xml version="1.0" encoding="utf-8"?>
<resources>
	<color name="colorPrimary">#0b6c63</color>
	<color name="colorPrimaryDark">#0a6058</color>
	<color name="colorAccent">#FF4081</color>
</resources>

3. Internet Permission in AndroidManifest file

In this project, we need to access internet to load the webpage. So, we will add internet permission in AndroidManifest.xml file. Add below code into src/main/AndroidManifest.xml file –

<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.tutorialwing.webview"
		  xmlns:android="http://schemas.android.com/apk/res/android">

	<uses-permission android:name="android.permission.INTERNET" />

	<application
		android:allowBackup="true"
		android:icon="@mipmap/ic_launcher"
		android:label="@string/app_name"
		android:roundIcon="@mipmap/ic_launcher_round"
		android:supportsRtl="true"
		android:theme="@style/AppTheme">

		<meta-data android:name="android.webkit.WebView.EnableSafeBrowsing"
				   android:value="false" />

		<activity android:name=".MainActivity">
			<intent-filter>
				<action android:name="android.intent.action.MAIN"/>

				<category android:name="android.intent.category.LAUNCHER"/>
			</intent-filter>
		</activity>
	</application>

</manifest>

Android WebView may upload anonymous diagnostic data to google when you have consented. Google use these data to improve webView. These data are collected on per-app basis for each app that use webView. If you want to opt out, i.e. do not want to send data to google, you can add below code into < application > element.

<manifest>
     <application>
         ...
         <meta-data android:name="android.webkit.WebView.MetricsOptOut"
             android:value="true" />
     </application>
 </manifest>

Note – Data is uploaded to google only if user has given permission and app has not opted out.

While using webView, If you want to block malicious url and show a warning UI to navigate back or proceed to malicious url, then, you need to add below code into < application > element.

<manifest>
     <application>
         ...
         <meta-data android:name="android.webkit.WebView.EnableSafeBrowsing"
             android:value="false" />
     </application>
</manifest>

4. How To Customise Android WebView

We can customise WebView in many ways. They are –
(a) Using WebViewClient – Use when you want to customise webView that impacts rendering of the content.
(b) Using WebChromeClient – Use it when you want to customise webView that impacts browser UI.
(c) Using WebSettings – We can modify the webSettings of WebView for task such as enabling javascript, setting whether you want to zoom in or zoom out a webpage etc.
(d) Injecting Java objects into the WebView using the addJavascriptInterface(Object, String) method. – This allows us to inject java object into page’s javascript context so that it can be accessed by javascript in the page.

4.1 Define WebChromeClient For Android WebView

If you want to customise the webView that might impact UI browser, then you need to use WebChromeClient class. This class is called in such situations. For example, Show progressBar while page is loading, show javascript alert etc.

Now, we are creating a class, subclassed from WebChromeClient, that will be used later in the application.
So, create a java file, WebChromeClt.java, in main/java/com.tutorialwing.webview folder. Then, add below code into it.

package com.tutorialwing.webview;

import android.app.Activity;
import android.webkit.WebChromeClient;
import android.webkit.WebView;

public class WebChromeClt extends WebChromeClient {

	private Activity activity;

	WebChromeClt(Activity activity) {
		this.activity = activity;
	}

	public void onProgressChanged(WebView view, int progress) {
		// The progress meter will automatically disappear when we reach 100%
		activity.setProgress(progress * 1000);
	}
}

In this file, we are showing progress meter that represents how much part of a page has been loaded.

4.2 Define WebViewClient For Android WebView

If you want to customise UI that might impact content rendering, then you need to use WebViewClient class. This class is called in such situations. For example, Error or Form submissions. You can also intercept URL loading here.

Now, we will create a class, subclassed from WebViewClient, that will be used later in the application. So, create a java file, WebViewClt.java, in main/java/com.tutorialwing.webview folder. Then, add below code into it.

package com.tutorialwing.webview;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class WebViewClt extends WebViewClient {

	private Activity activity;

	WebViewClt(Activity activity) {
		this.activity = activity;
	}

	@Override
	public boolean shouldOverrideUrlLoading(WebView webView, String url) {
		if (url.contains("https://tutorialwing.com"))
			return false;

		Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
		activity.startActivity(intent);
		return true;
	}

	@Override
	public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
			Toast.makeText(activity, "Got Error! " + error, Toast.LENGTH_SHORT).show();
	}
}

In this file, we are performing two methods –
– 1. shouldOverrideUrlLoading( . . . ) – This method provides host application a chance to take over the control when a new url is about to be loaded. If it is not provided, WebView will ask Activity Manager to choose proper handler for it. If it is provided and returns false, it means current webView will handle the url. If it returns true, it means host application handles the url.

– 2. onReceivedError( . . .) – This method reports web resource loading error to the host application.

4.3 Use WebSetting to Customise Android WebView

WebSetting manages settings of a WebView. Whenever a WebView is created, a default settings is attached with it. You can get it using getSettings() method. This webSettings object is tied to the lifecycle of WebView. If webView has been destroyed, any method call on webSettings object will return IllegalStateException.

You can perform below task using webSettings –
(a) You can enable javascript. You can do it as below –

WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);

(b) You can enable built-in zoom. You can do it as below –

WebSettings webSettings = webView.getSettings();
webSettings.setBuiltInZoomControls(true);

5. Use WebView Widget in xml file

Open res/layout/activity_main.xml file. Then, add below code into it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="match_parent"
	android:layout_height="match_parent">

	<WebView
		android:id="@+id/webView"
		android:layout_width="match_parent"
		android:layout_height="match_parent"/>

</LinearLayout>

It is recommended to set webView height to either fixed value or MATCH_PARENT. When using MATCH_PARENT, none of it’s parent should use WRAP_PARENT because that could result in incorrect sizing of the views.

When you set Android WebView height to WRAP_PARENT,
(a) It enable HTML body height to set a fixed height. So, This means element with height relative to HTML body may not be sized correctly.
(b) For applications targeting KITKAT and earlier SDKs the HTML viewport meta tag will be ignored in order to preserve backwards compatibility.

6. Load Data Into Android WebView From Different Sources

We can load a page in WebView in below ways –
(a) A Page with given url.
(b) Create your own html page and load it into webView.
(c) Create a webpage by using data stored locally and then load it into webView.

Now, we will go through each way one by one.

6.1 Load WebPage With Given URL into Android WebView

Open src/main/java/com.tutorialwing.webview/MainActivity.java file. Then, add below code into it.

package com.tutorialwing.webview;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity {

	private WebView webView = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		getWindow().requestFeature(Window.FEATURE_PROGRESS);

		setContentView(R.layout.activity_main);

		webView = findViewById(R.id.webView);
		if (webView != null) {


			WebSettings webSettings = webView.getSettings();
			webSettings.setJavaScriptEnabled(true);

			webSettings.setBuiltInZoomControls(true);

			webView.setWebViewClient(new WebViewClt(this));
			webView.setWebChromeClient(new WebChromeClt(this));

			webView.loadUrl(getString(R.string.site_url));
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK) && this.webView.canGoBack()) {
			webView.goBack();
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}
}
6.2 Create Custom HTML WebPage And Load into Android WebView

Open src/main/java/com.tutorialwing.webview/MainActivity.java file. Then, add below code into it.

package com.tutorialwing.webview;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity {

	private WebView webView = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		getWindow().requestFeature(Window.FEATURE_PROGRESS);

		setContentView(R.layout.activity_main);

		webView = findViewById(R.id.webView);
		if (webView != null) {

			WebSettings webSettings = webView.getSettings();
			webSettings.setJavaScriptEnabled(true);

			webSettings.setBuiltInZoomControls(true);

			webView.setWebViewClient(new WebViewClt(this));
			webView.setWebChromeClient(new WebChromeClt(this));

			// Case 2 .. Create your own html page...
			webView.loadData("<html><body>Hello, world!</body></html>", "text/html", "UTF-8");
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK) && this.webView.canGoBack()) {
			webView.goBack();
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}
}
6.3 Show Data of Given File Path into Android WebView

Open src/main/java/com.tutorialwing.webview/MainActivity.java file. Then, add below code into it.

package com.tutorialwing.webview;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity {

	private WebView webView = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		getWindow().requestFeature(Window.FEATURE_PROGRESS);

		setContentView(R.layout.activity_main);

		webView = findViewById(R.id.webView);
		if (webView != null) {

			WebSettings webSettings = webView.getSettings();
			webSettings.setJavaScriptEnabled(true);

			webSettings.setBuiltInZoomControls(true);

			webView.setWebViewClient(new WebViewClt(this));
			webView.setWebChromeClient(new WebChromeClt(this));

			// Case 3 .. Show data in the file path...
			String html = "<html><head><title>TITLE!!!</title></head>";
			html += "<body><h3>Tutorial by tutorialwing.com</h3><img src=\"ic_launcher.png\" /></body></html>";

			// Provide relative url to the base...
			String baseUrl = "file:///android_res/mipmap/";
			String data = html;
			String mimeType = "text/html";
			String encoding = "UTF-8";
			String historyUrl = null;

			webView.loadDataWithBaseURL(baseUrl, data, mimeType, encoding, historyUrl);
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK) && this.webView.canGoBack()) {
			webView.goBack();
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}
}

In this tutorial, we have shown many ways to load data into android webView. However, you can use any way based on your requirements to load data into webView.

For the sake of completeness of this tutorial, we have used method 1 (load data into webView with given url). When we run the program, we will get output as shown above.

That’s end of tutorial on Android WebView widget.

Leave a Reply