Android – WebViewClient example

By -
Problem: WebViewClient tutorial

Demo of creating an application to open any URL inside the application and clicking on any link from that URl
should not open Native browser but that URL should open in the same screen.

Output:

android webviewclient demo

Solution:

WebViewClientDemoActivity.java

package com.paresh.webviewclientdemo;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;

/*
 * Demo of creating an application to open any URL inside the application and clicking on any link from that URl
should not open Native browser but  that URL should open in the same screen.
 */
public class WebViewClientDemoActivity extends Activity {
    /** Called when the activity is first created. */

	WebView web;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        web = (WebView) findViewById(R.id.webview01);
        web.setWebViewClient(new myWebClient());
        web.getSettings().setJavaScriptEnabled(true);
        web.loadUrl("http://www.google.com");
    }

    public class myWebClient extends WebViewClient
    {
    	@Override
    	public void onPageStarted(WebView view, String url, Bitmap favicon) {
    		// TODO Auto-generated method stub
    		super.onPageStarted(view, url, favicon);
    	}

    	@Override
    	public boolean shouldOverrideUrlLoading(WebView view, String url) {
    		// TODO Auto-generated method stub

    		view.loadUrl(url);
    		return true;

    	}
    }

    // To handle "Back" key press event for WebView to go back to previous screen.
   @Override
   public boolean onKeyDown(int keyCode, KeyEvent event)
  {
 	if ((keyCode == KeyEvent.KEYCODE_BACK) && web.canGoBack()) {
		web.goBack();
		return true;
	}
	return super.onKeyDown(keyCode, event);
   }
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

   <TextView
       android:layout_height="wrap_content"
       android:layout_width="fill_parent"
       android:text="This is the demo of WebView Client"
       android:textSize="20sp"
       android:gravity="center_horizontal">       
   </TextView>
   
   <WebView
       android:id="@+id/webview01"
       android:layout_height="wrap_content"
       android:layout_width="fill_parent"
       android:layout_weight="1">
   </WebView>
   
   <ImageView 
       android:src="@drawable/ic_launcher"
       android:layout_height="wrap_content"
       android:layout_width="fill_parent"/>  	

</LinearLayout>

Download example: https://github.com/PareshMayani/Android-WebViewClient-Example

Paresh Mayani

Paresh Mayani is a lead android developer from India. Currently, He is Sr. Software engineer at InfoStretch Solutions Pvt. Ltd. He has been developing android apps since very 1st version i.e. Android 1.5, he says he has seen days and nights of Android history. He is the Head/Organizer of Google Developers Group (GDG), Ahmedabad

  • http://jignesh259.wordpress.com/ Jignesh

    Hi,
    Really nice and helpful.
    Keep it up :)

    • http://www.technotalkative.com/ Paresh N. Mayani

      Thanx Jignesh.

  • enl8enmentnow

    Why don’t you just have 
    shouldOverrideUrlLoading return false?

  • http://www.mtrig.com/ MTR Investors Group

    Great example. I am looking at webview as a way to publish some of our website features and attempt a code once method and publish via webview on Android and IOS.

    • Nezam Uddin

      go for titainium javascript api for writing native cross platform code

  • mayur

    Thanks

  • Basith

    nice tutoial….its very helpful for begineers…….Thanks

    Paresh Mayani

    • http://www.technotalkative.com/ Paresh Mayani

      Welcome, I am glad it has helped you. Cheers !!

  • Amit Bhaliya

    package in.wptrafficanalyzer.listviewwithimagesandtext;

    import java.util.ArrayList;

    import java.util.HashMap;

    import java.util.List;

    import android.app.Activity;

    import android.os.Bundle;

    import android.widget.ListView;

    import android.widget.SimpleAdapter;

    public class MainActivity extends Activity {

    // Array of strings storing country names

    String[] countries = new String[] {

    “India”,

    “Pakistan”,

    “Sri Lanka”,

    “China”,

    “Bangladesh”,

    “Nepal”,

    “Afghanistan”,

    “North Korea”,

    “South Korea”,

    “Japan”

    };

    // Array of integers points to images stored in /res/drawable-ldpi/

    int[] flags = new int[]{

    R.drawable.india,

    R.drawable.pakistan,

    R.drawable.srilanka,

    R.drawable.china,

    R.drawable.bangladesh,

    R.drawable.nepal,

    R.drawable.afghanistan,

    R.drawable.nkorea,

    R.drawable.skorea,

    R.drawable.japan

    };

    // Array of strings to store currencies

    String[] currency = new String[]{

    “Indian Rupee”,

    “Pakistani Rupee”,

    “Sri Lankan Rupee”,

    “Renminbi”,

    “Bangladeshi Taka”,

    “Nepalese Rupee”,

    “Afghani”,

    “North Korean Won”,

    “South Korean Won”,

    “Japanese Yen”

    };

    /** Called when the activity is first created. */

    @Override

    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    // Each row in the list stores country name, currency and flag

    List<HashMap> aList = new ArrayList<HashMap>();

    for(int i=0;i<10;i++){

    HashMap hm = new HashMap();

    hm.put(“txt”, “Country : ” + countries[i]);

    hm.put(“cur”,”Currency : ” + currency[i]);

    hm.put(“flag”, Integer.toString(flags[i]) );

    aList.add(hm);

    }

    // Keys used in Hashmap

    String[] from = { “flag”,”txt”,”cur” };

    // Ids of views in listview_layout

    int[] to = { R.id.flag,R.id.txt,R.id.cur};

    // Instantiating an adapter to store each items

    // R.layout.listview_layout defines the layout of each item

    SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.listview_layout, from, to);

    // Getting a reference to listview of main.xml layout file

    ListView listView = ( ListView ) findViewById(R.id.listview);

    // Setting the adapter to the listView

    listView.setAdapter(adapter);

    }

    }

    how to add hyperlink in above code so please help to me send me reply on this id amit.potent@gmail.com

  • Jiahao Liu

    You must add the internet permission to make it works.

    • http://www.technotalkative.com/ Paresh Mayani

      Yes that’s the first and for most thing to include in AndroidManifest.xml whenever you require internet access in app. Thanks

  • Mahbubur Rahman Turzo

    Excellent tutorial! :D

  • DomenicoButtafarro

    Hi, thanks but can add GDC for send notifich push?

    Thanks