Android WebView

WebView widget can be defined as below –

"Android WebView is used to display web page in android. You can load the web page from the same application or url. It is used to display content online in android activity."

WebView uses webkit rendering engine to –

  • Display webpages.
  • Includes methods to navigate forward and backward through history. 
  • Zoom in zoom out.
  • Text Searches.
  • Javascript and many more things.

 

 

 

 

Some of the popular attributes of android webView –

S. No. XML Attributes Description
1 android:id This is unique id of the WebView to uniquely identify the WebView.
2 android:height Height of the WebView.
3 android:width Width of the WebView.
4 android:alpha Defines alpha of the view.
5 android:background Defines drawable to be used for the background.
6 android:contextClickable Defines whether this view should react to context click event.
7 android:elevation Defines base z depth of the view.
8 android:fitsSystemWindows It is used to adjust view layout based on system windows such as status bar etc. It accepts true or false value.
9 android:foreground Defines the drawable to draw over the content.
10 android:foregroundGravity Defines the gravity of the foreground drawable.
11 android:clipChildren Defines whether a child is limited to draw inside of its bounds or not.
12 android:layoutAnimation Defines the layout animation to use when the viewGroup is laid out for the first time.
13 android:persistentDrawingCache Defines the persistent of the drawing cache.
14 android:layoutMode Defines layout mode this viewGroup.

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

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

S. No. Steps
1 Open Android Studio.
2 Click on Start a new Android Studio Project Write application name as WebView. Then, click next button.
3 Select minimum SDK you need. However, we have selected 14 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 tutorial  to Create a New Project to know steps in detail.

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

 

 

 

 

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

<resources>
<string name="app_name">WebView</string>
<string name="website_url">https://ukacademe.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. We 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">#008577</color>
<color name="colorPrimaryDark">#00574B</color>
<color name="colorAccent">#D81B60</color>
</resources>

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

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

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

<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">
<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 a per-app basis for each app that uses 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> 

We can customise WebView in many ways. They are –

  • Using WebViewClient – Use when you want to customise webView that impacts rendering of the content.
  • Using WebChromeClient – Use it when you want to customise webView that impacts browser UI.
  • 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.
  • 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.

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

You can perform below task using webSettings –

  • You can enable javascript. You can do it as below –
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
  • You can enable built-in zoom. You can do it as below –
WebSettings webSettings = webView.getSettings();
webSettings.setBuiltInZoomControls(true);

 

 

 

 

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

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

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

</android.support.constraint.ConstraintLayout> 

It is recommended that webView height be set to either a fixed value or MATCH_PARENT. When using MATCH_PARENT, none of its parent should use WRAP_PARENT because this could result in incorrect views sizing.

When you set Android WebView height to WRAP_PARENT,

  • 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.
  • For applications targeting KITKAT and earlier SDKs the HTML viewport meta tag will be ignored in order to preserve backwards compatibility.

We can load a page in WebView in below ways –

  • A Page with given url.
  • Create your own html page and load it into webView.
  • Create a webpage by using data stored locally and then load it into webView.
package com.ukacademe.webview;

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

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().requestFeature(Window.FEATURE_PROGRESS);
        setContentView(R.layout.activity_main);

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


            WebSettings webSettings = webView.getSettings();
            webSettings.setJavaScriptEnabled(true);
            webView.loadUrl("https://www.ukacademe.com");
            webView.setWebViewClient(new WebViewClient() {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    // TODO Auto-generated method stub

                    view.loadUrl(url);
                    return true;

                }
            });

        }
    }

}

When we run the appilcation, we will get output as shown below.

UK Academe-WebView-Output