Android WebView Tutorial

person folder_openAndroidaccess_time March 19, 2015

In this tutorial we are going to show how to load web pages inside android application. It is possible to load web sites in our android application using WebView.
See flowing Steps :

  1. Create a layout file res/layout/activity_main.xml with one WebView in it.
  2. In MainActivity.java create a new custom WebViewClient and attach it to the webview widget.
  3. In Manifest file, declare the INTERNET permission.

Note: You have to use a custom WebViewClient and override the method shouldOverrideUrlLoading. Otherwise the inks will be opened in the default web browser application.

1. Manifest file
INTERNET permission is required to load web pages in your application.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.stackandroid.webview"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="21" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/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>

2. Activity layout file
We can also add other widgets like TextView, EditText, Button, etc., in the same activity.

<?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" >
   <WebView
    android:id="@+id/webView1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
/>
</LinearLayout>

3. Main Activity code
Create a new custom WebViewClient and override the method shouldOverrideUrlLoading. You can add javascript support setJavaScriptEnabled.

To load a website by url, we have to use loadUrl method. Android WebView supports offline pages and direct HTML content also. To load offline web pages (ie. web pages from within the application), all the HTML, CSS, Javascript files should be available inside the assets folder and use loadUrl  method. Use loadData to load constructed HTML string.

package com.stackandroid.webview;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends Activity {
    //private Button button;
    private WebView webView;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Get webview
        webView = (WebView) findViewById(R.id.webView1);
        startWebView("http://www.stackandroid.com");
    }
    @SuppressLint("JavascriptInterface")
	private void startWebView(String url) {
        //Create new webview Client to show progress dialog
        //When opening a url or click on link
        webView.setWebViewClient(new WebViewClient() {
            ProgressDialog progressDialog;
            //If you do not use this method url links are opeen in new brower not in webview
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
            //Show loader on url load
            public void onLoadResource (WebView view, String url) {
                if (progressDialog == null) {
                    // in standard case YourActivity.this
                    progressDialog = new ProgressDialog(MainActivity.this);
                    progressDialog.setMessage("Loading...");
                    progressDialog.show();
                }
            }
            public void onPageFinished(WebView view, String url) {
                try{
                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                    progressDialog = null;
                }
                }catch(Exception exception){
                    exception.printStackTrace();
                }
            }
        });
         // Javascript inabled on webview
        webView.getSettings().setJavaScriptEnabled(true);
        // Other webview options
        /*
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        webView.setScrollbarFadingEnabled(false);
        webView.getSettings().setBuiltInZoomControls(true);
        */
        /*
         String summary = "<html><body>You scored <b>192</b> points.</body></html>";
         webview.loadData(summary, "text/html", null);
         */
        //Load url in webview
        webView.loadUrl(url);
    }
    // Open previous opened link from history on webview when back button pressed
    @Override
    // Detect when the back button is pressed
    public void onBackPressed() {
        if(webView.canGoBack()) {
            webView.goBack();
        } else {
            // Let the system handle the back button
            super.onBackPressed();
        }
    }
}

4. Demonstration

Web site loaded in webview
Web site loaded in webview

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">