Learn Android UI

WebView Tutorial With Example In Android Studio

In Android, WebView is a view used to display the web pages in application. This class is the basis upon which you can roll your own web browser or simply use it to display some online content within your Activity. We can also specify HTML string and can show it inside our application using a WebView. Basically, WebView turns application into a web application.

WebView in Android
In order to add Web View in your application, you have to add <WebView> element to your XML( layout ) file or you can also add it in java class.

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

Internet Permission Required For Webview:

Important Note: In order for Activity to access the Internet and load the web pages in a WebView, we must add the internet permissions to our Android Manifest file (Manifest.xml).

Below code define the internet permission in our manifest file to access the internet in our application.

<!--Add this before application tag in AndroidManifest.xml-->
<uses-permission android:name="android.permission.INTERNET" />

Intenet Permission AndroidManifest Code For WebView


Methods of WebView In Android:

Let’s discuss some common methods of a Webview which are used to configure a web view in our application.

loadUrl() – Load a web page in our WebView

loadUrl(String 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.

Below we load a url: https://abhiandroid.com/ui/ in our application.

/*Add in Oncreate() funtion after setContentView()*/
// initiate a web view
WebView simpleWebView=(WebView) findViewById(R.id.simpleWebView);
// specify the url of the web page in loadUrl function
simpleWebView.loadUrl("https://abhiandroid.com/ui/");

loadUrl in Webview Android
2. loadData() – Load Static Html Data on WebView

  loadData(String data, String mimeType, String encoding) 

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.

Below we load the static Html string data in our application of a web view.

/*Add in Oncreate() funtion after setContentView()*/
// initiate a web view
WebView webView = (WebView) findViewById(R.id.simpleWebView);
// static html string data
String customHtml = "<html><body><h1>Hello, AbhiAndroid</h1>" +
        "<h1>Heading 1</h1><h2>Heading 2</h2><h3>Heading 3</h3>" +
        "<p>This is a sample paragraph of static HTML In Web view</p>" +
        "</body></html>";
// load static html data on a web view
webView.loadData(customHtml, "text/html", "UTF-8");

loadData in WebView Android
3. Load Remote URL on 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.

Below we load a url by using web view client in a WebView.

/*Add in Oncreate() funtion after setContentView()*/
// initiate a web view
 simpleWebView = (WebView) findViewById(R.id.simpleWebView);

// set web view client
 simpleWebView.setWebViewClient(new MyWebViewClient());

// string url which you have to load into a web view
 String url = "https://abhiandroid.com/ui/";
 simpleWebView.getSettings().setJavaScriptEnabled(true);
 simpleWebView.loadUrl(url); // load the url on the web view
 }

 // custom web view client class who extends WebViewClient
 private class MyWebViewClient extends WebViewClient {
 @Override
 public boolean shouldOverrideUrlLoading(WebView view, String url) {
 view.loadUrl(url); // load the url
 return true;
 }

4. canGoBack() – Move to one page back if a back history exist

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.

Below we check whether a web view has back history or not.

// initiate a web view
WebView simpleWebView=(WebView)findViewById(R.id.simpleWebView);
// checks whether a web view has a back history item or not
Boolean canGoBack=simpleWebView.canGoBack();

5. canGoForward() – Move one page forward if forward history exist

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.

Below we check whether a web view has forward history or not.

// initiate a web view
 WebView simpleWebView=(WebView)findViewById(R.id.simpleWebView);
// checks whether a web view has a forward history item or not
 Boolean canGoForword=simpleWebView.canGoForward() ;

6. clearHistory() – clear the WebView history

This method is used to clear the web view forward and backward history.

Below we clear the forword and backword history of a WebView.

WebView simpleWebView=(WebView)findViewById(R.id.simpleWebView); // initiate a web view
simpleWebView.clearHistory(); // clear the forward and backward history

WebView Example In Android Studio:

Here in this WebView example we show the use of web view in our application. To do that we display two buttons one is for displaying a web page and other is for displaying static HTML data in a web view. Below is the final output, download code and step by step explanation:

Download Code ?

WebView Example in Android Studio
Step 1: Create a new project and name it WebViewExample

Select File -> New -> New Project… then Fill the forms and click "Finish" button.

Step 2: Open res -> layout -> activity_main.xml (or) main.xml and add following code :

In this step we open an XML file and add the code for displaying two buttons and a Webview in our xml file ( layout ).

<LinearLayout 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"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="2">

        <Button
            android:id="@+id/loadWebPage"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dp"
            android:layout_weight="1"
            android:background="#444"
            android:text="Load Web Page"
            android:textColor="#fff"
            android:textSize="14sp"
            android:textStyle="bold" />

        <Button
            android:id="@+id/loadFromStaticHtml"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_weight="1"
            android:background="#444"
            android:text="Load Static HTML"
            android:textColor="#fff"
            android:textSize="14sp"
            android:textStyle="bold" />
    </LinearLayout>

    <WebView
        android:id="@+id/simpleWebView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_marginTop="20dp"
        android:scrollbars="none" />

</LinearLayout>

Step 3: Open   src -> package -> MainActivity.java

In this step we open MainActivity and add the code to initiate the web view and two buttons. Out of those one button is used for displaying a web page in a webview and other one is used to load a static HTML page in webview.

package example.gb.webviewexample;

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

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    WebView simpleWebView;
    Button loadWebPage, loadFromStaticHtml;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // initiate buttons and a web view
        loadFromStaticHtml = (Button) findViewById(R.id.loadFromStaticHtml);
        loadFromStaticHtml.setOnClickListener(this);
        loadWebPage = (Button) findViewById(R.id.loadWebPage);
        loadWebPage.setOnClickListener(this);
        simpleWebView = (WebView) findViewById(R.id.simpleWebView);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.loadFromStaticHtml:
                // define static html text
                String customHtml = "<html><body><h1>Hello, AbhiAndroid</h1>" +
                        "<h1>Heading 1</h1><h2>Heading 2</h2><h3>Heading 3</h3>" +
                        "<p>This is a sample paragraph of static HTML In Web view</p>" +
                        "</body></html>";
                simpleWebView.loadData(customHtml, "text/html", "UTF-8"); // load html string data in a web view
                break;
            case R.id.loadWebPage:
                simpleWebView.setWebViewClient(new MyWebViewClient());
                String url = "https://abhiandroid.com/ui/";
                simpleWebView.getSettings().setJavaScriptEnabled(true);
                simpleWebView.loadUrl(url); // load a web page in a web view
                break;
        }
    }

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

    
}

Step 4: Open manifests -> AndroidManifest.xml

In this step we open Manifest file and define the internet permission for our app.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="example.gb.webviewexample">
    <!-- define internet permission for our app -->
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

 Output:

Now start the AVD in Emulator and run the App. Choose either to open webpage or static HTML in WebView by clicking on Button. We open static HTML.

WebView Example Output Android
 


How to add progressBar in webview & convert website into advance android app

 

Convert-website-into-advance-android-app-banner

Convert Website Into App Using WebView:

Now you have learn WebView, so why not try converting any website into Android App? Read our advance WebView Android App tutorial to learn how to do it easily.

DOWNLOAD THIS FREE eBook!

This free eBook will help you master the learning of Android App Development in Android Studio!

7 thoughts on “WebView Tutorial With Example In Android Studio”

  1. Hello sir

    ThAnkyou for this tutorial,

    I have a question-
    Main actvity XML file have 2 buttons frist btn click then open browser activity and show web page I m set a url in browser activity and implement some features of browser activity like bookmarks, scroll down to hide app bar and many more .But
    How to set second button to load diffrent url in same browsers activity
    Plz sir reply

    Waiting for your reply

    Thank you

Leave a Reply to HienPham Cancel reply

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



Continue Reading:

Download Free - Master Android App Development Sidebar

DOWNLOAD THIS FREE eBook!

This free eBook will help you master the learning of Android App Development in Android Studio!
close-link

Android Developer Facebook Group Free

Premium Project Source Code:




DOWNLOAD THIS FREE eBook!

This free eBook will help you master the learning of Android App Development in Android Studio!
close-link

DOWNLOAD THIS FREE eBook!

This free eBook will help you master the learning of Android App Development in Android Studio!
close-link

DOWNLOAD THIS FREE eBook!

This free eBook will help you master the learning of Android App Development in Android Studio!
close-link

See How AbhiAndroid Step By Step Video Training Helps You Master Android App Development

Video Training - Unlock step by step video training with new content added regularly. Develop Android Apps.
Android App Source Code - Get amazing Ecommerce, Food Ordering and Ultimate WebView source code with documentation.
GET ACCESS NOW
close-link

With a very poor revenue from selling source code files or using Google AdSense, we need your help to survive this website. Please contribute any amount you can afford
Pay
* Terms & Conditions Apply
close-link