WebView in Android | AndroidMonks

 WebView in Android with Example

In Android, WebView is used to show the WebSite inside your Android application. This seems pretty straightforward, but there are some important concepts to understand to create a good neater looking Web View. We will be depending on the Web View Tag and the Class to Load, show and change URL inside the App.

However, it is important to understand right at the start that, creating a Website and using that inside a WebView to create an Application is a Bad practice, and looses customer interest. 

YOU ARE YOUR BOSS
I agree to have my personal information transfered to MailChimp ( more information )
Join over 5.000 visitors who are receiving our free content and learn how to program with Android. The growth of Android is estimated to reach a whooping 83% by 2020. Hop on the train and start making money!
We hate spam. Your email address will not be sold or shared with anyone else.

The Web View was primarily created to show only important disclaimer pages, privacy pages inside the View which needn’t hold a Activity and resource unnecessarily!

Check out the Definition and Implementation of the WebView below.

WebView – Basic Implementation

In order to use the Web View in your application, you will need the WebView Tag like below.

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

Just as any other view, layout_height and layout_width are the default views required. Once this is done, we can go ahead and look at additional properties related to of a Web View.

Web View inherits all the attributes of a View and ViewGroup, to know about the attributes check here.

WebView – Public Methods

This is a list of all the frequently used methods of a WebView.

addJavascriptInterface(Object object, String name)

Just as the name suggests, it allows addition of Java Object into the WebView.

autofill(SparseArray<AutofillValue> values)

Automatically fills the content of the Virtual Children within this View, which means that it allows auto fill of a Field just like it was done in a website.

canGoBack()

Implementing a Web View alone wont be required. Incase, the user presses the back button, this canGoBack() method checks if there is a back history, like we do with a Browser and loads the previous page from history, instead of making the Back button callback work in the Activity.

canGoBackOrForward(int steps)

This method is similar to that of the canGoBack() callback, gets whether the page can go back or forward the given number of steps.

canGoForward()

Gets whether this Web View has a forward history item.

clearCache(boolean includeDiskFiles)

This method clears the cache like we do in our web browser

clearHistory()

Tells this Web View to clear its internal back/forward list.

destroy()

Destroys the internal state of this WebView.

loadUrl(String url)

Important method that loads the given URL

loadData(String data, String mimeType, String encoding)

Loads the given data into this WebView using a ‘data’ scheme URL,

These are some frequently used methods in WebView class. Additionally, check out the list of entire callbacks for WebView.

WebView – Using Internet Permissions

What’s more important is to let the application we are using to allow Internet! This is possible only by setting the allow-permission tag in Manifest like below.

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

Check out the Image below for clearer understanding

Manifest Permission
Manifest Permission

Create a Simple WebView Application loading a Static Content

In this application we will use the loadData() method and create a static content Web View in our application.

Creating the layout_webview.xml

<?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"
    android:orientation="vertical">
    <Button
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Load Data"
        android:layout_gravity="center"
        android:id="@+id/loadData"/>
    <WebView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/webView"/>

</LinearLayout>

WebViewActivity.java

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;

public class WebViewActivity extends AppCompatActivity{
    WebView webView;
    Button button;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webview_layout);
        webView = findViewById(R.id.webView);
        button = findViewById(R.id.loadData);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String customHtml = "<html><body><h1>This is a great example</h1>" +
                        "<h1>Hello Monks!</h1><h2>Learn More content</h2><h3>Easily</h3>" +
                        "<p>Loaded a sample Static Content Site! Can also load a URL resource!</p>" +
                        "</body></html>";
                webView.loadData(customHtml, "text/html", "UTF-8");

            }
        });
    }
}

The resulting Application is

"<yoastmark

Creating a WebView to load a Sample URL

This can be done using the loadUrl() method. However, it is important to note that, in order to open a hyperlink, within the Web View itself, we will need to override the class WebViewClient. This is done, in order to make sure, we have a interface for all the URL’s to be loaded.

The implementation is as given below.

We will re-use the same layout as above. Additionally, we will be creating a Interface name WebViewLoaderClient and using that to set to our Web View client object. This will fire each URL inside the WebView like we expect it to.

WebViewActivity.java

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;

public class WebViewActivity extends AppCompatActivity{
    WebView webView;
    Button button;
    String URL;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webview_layout);
        URL = "https://www.androidmonks.com";
        webView = findViewById(R.id.webView);
        button = findViewById(R.id.loadData);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               webView.setWebViewClient(new WebViewLoaderClient());
               webView.getSettings().setLoadsImagesAutomatically(true);
               webView.getSettings().setJavaScriptEnabled(true);
               webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
               webView.loadUrl(URL);

            }
        });
    }
private class WebViewLoaderClient extends WebViewClient{
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}
}

This now creates a Web View application like below.

"<yoastmark

"<yoastmark

This is a helpful View, where we can play with lot of Web related changes and it will still reflect here. However, it cannot replace a Native Android Application at any point in time. It is highly reliant on the data connection of the user’s phone, hence, can load data very slowly.

Drop in any comments below.

“Learn and Be Curious”

 

 

 

Also Read  AsyncTask with Progressbar Example | AndroidMonks

Leave a Comment

Your email address will not be published. Required fields are marked *