WebView

Android WebView component is a full-fledged browser implemented as a View subclass to embed it into our android application. WebView allows you to integrate a webpage as a part of the app. WebView comes with all the features that of a desktop browser like managing history, cookies, HTML5 support and lot more. Using webview you can build very cool apps like integrating HTML5 games in the app.

Let's create an example to understand WebView, first we create webview_activity.xml

webview_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/webView"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Now create WebViewActivity.java
package com.theitbulls.uicomponentex;

import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class WebViewActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webview_activity);

        WebView webView = findViewById(R.id.webView);
        webView.setWebViewClient(new WebViewClient());

        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl("http://theitbulls.com/android/");
    }
}


We will discuss now common methods of WebView

Supporting JavaScript: JavaScript is by default turned off in WebView widgets. Hence web pages containing javascript references won't work properly. To enable java script the following snippet needs to be called on the WebView instance

webView.getSettings().setJavaScriptEnabled(true);

Load URL: This function is used to load a web page in a web view of our application. In this method we specify the url of the web page that should be loaded in a web view.

webView.loadUrl("http://theitbulls.com/android/");

Load Data: This method is used to load the static HTML string in a web view. loadData() function takes html string data, mime-type and encoding param as three parameters.

String htmlData = "<html>" + //
        "<head></head>" + //
        "<body>" + //
                "Hello this is Android WebView example" + //
        "</body>" + //
        "</html>";
webView.loadData(htmlData, "text/html", "UTF-8");


Load data from base url: This takes, among other parameters, the base URL to use when resolving relative URLs in the HTML. Any relative URL (e.g., <img src="./img1.png">) will be interpreted as being relative to the base URL supplied to loadDataWithBaseURL(). See example ahead

String baseUrl = "http://theitbulls.com";
String htmlData = "<img src=\"./imgs/img1.jpg\" width=\"400px\" height=\"250px\">";
String mimeType = "text/html";
String encoding = "UTF-8";
String historyUrl = "https://theitbulls.com";
webView.loadDataWithBaseURL(baseUrl, htmlData, mimeType, encoding, historyUrl);

WebView using WebViewClient: WebViewClient help us to monitor event in a WebView. You have to Override the shouldOverrideUrlLoading() method. This method allow us to perform our own action when a particular url is selected. Once you are ready with the WebViewClient, you can set the WebViewClient in your WebView using the setWebViewClient() method.

The default behavior when a user clicks on a link inside the web page is to open the systems default browser app. This can break the user experience of the app users. To keep page navigation within the WebView and hence within the app, we need to create a subclass of WebViewClient, and override its shouldOverrideUrlLoading(WebView webView, WebResourceRequest request) method.

Example:

webView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return false
        }
});


To distinguish between the URLs that are loaded within the app and browser the following code needs to be added in the shouldOverrideUrlLoading() method like:

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // this method deprecated
            // shouldOverrideUrlLoading(WebView view, String url) {
            if(url.indexOf("theitbulls") != -1) {
                        return false;
            }
            return true;
}

shouldOverrideUrlLoading(WebView view, String url) method has deprecated we must override shouldOverrideUrlLoading(WebView view, WebResourceRequest request) as shown below:

@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                        String url = request.getUrl().toString();
                        Log.d("Url: ", url);
                        if (url.indexOf("theitbulls") != -1) {
                                    return false;
                        }
            }
            return true;
}

CanGoBack: This method is used to specify whether the web view has a back history item or not. This method returns a Boolean value either true or false. If it returns true then goBack() method is used to move one page back. We can override onBackPressed() method of activty as shown below

@Override
public void onBackPressed() {
        if(webView.canGoBack()) {
            webView.goBack();
            return;
        }
        super.onBackPressed();
}

Or

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

        return super.onKeyDown(keyCode, event);
}

CanGoForward: This method is used to specify whether the web view has a forword history item or not. This method returns a Boolean value either true or false. If it returns true then goForword() method is used to move one page forword, following code snippet show you how it work:

if(webView.canGoForward()) {
        webView.goForward();
}


Clear History: This method is used to clear the web view forward and backward history. And Clear Cache: This method is used to clear cache. Below code snippet show you how:

webView.clearHistory();
webView.clearCache(true);