Android WebView example

Android’s WebView allows you to open an own windows for viewing URL or custom html markup page.

In this tutorial, you will create two pages, a page with a single button, when you clicked on it, it will navigate to another page and display URL “google.com” in WebView component.

P.S This project is developed in Eclipse 3.7, and tested with Android 2.3.3.

1. Android Layout Files

Create two Android layout files – “res/layout/main.xml” and “res/layout/webview.xml“.

File : res/layout/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" >
 
    <Button
        android:id="@+id/buttonUrl"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Go to http://www.google.com" />
            
</LinearLayout>

File : res/layout/main.xml – WebView example


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

2. Activity

Two activity classes, an activity to display a button, another activity display the WebView with predefined URL.

File : MainActivity.java


package com.mkyong.android;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

	private Button button;

	public void onCreate(Bundle savedInstanceState) {
		final Context context = this;

		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		button = (Button) findViewById(R.id.buttonUrl);

		button.setOnClickListener(new OnClickListener() {

		  @Override
		  public void onClick(View arg0) {
		    Intent intent = new Intent(context, WebViewActivity.class);
		    startActivity(intent);
		  }

		});

	}

}

File : WebViewActivity.java


package com.mkyong.android;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;

public class WebViewActivity extends Activity {

	private WebView webView;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.webview);

		webView = (WebView) findViewById(R.id.webView1);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.loadUrl("http://www.google.com");

	}

}

3. Android Manifest

WebView required INTERNET permission, add below into AndroidManifest.xml.


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

File : AndroidManifest.xml – See full example.


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mkyong.android"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" />

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".WebViewActivity"
            android:theme="@android:style/Theme.NoTitleBar" />
        
        <activity
            android:label="@string/app_name"
            android:name=".MainActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

4. Demo

By default, just display a button.

android webview example

Click on button, WebView is display.

android webview example

5. Demo, Again

WebView allow you to manually load custom HTML markup, via webView.loadData(), see modified version :


package com.mkyong.android;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;

public class WebViewActivity extends Activity {

	private WebView webView;

	public void onCreate(Bundle savedInstanceState) {
	   super.onCreate(savedInstanceState);
	   setContentView(R.layout.webview);

	   webView = (WebView) findViewById(R.id.webView1);
	   webView.getSettings().setJavaScriptEnabled(true);
	   //webView.loadUrl("http://www.google.com");

	   String customHtml = "<html><body><h1>Hello, WebView</h1></body></html>";
	   webView.loadData(customHtml, "text/html", "UTF-8");

	}

}

Now, when button is clicked, a custom html page is displayed.

android webview example

Download Source Code

Download it – Android-WebView-Example.zip (16 KB)

References

  1. Official Android webView example
  2. Android WebView Javadoc
  3. Switching Android activity

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Mukesh Yadav
Guest
Mukesh Yadav

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 .But
How to set second button to load diffrent url in same browsers activity
Plz sir reply

Waiting for your reply

Thank you

Omar
Guest
Omar

hey mkyong,

first of all a big thank you made my day with these android tutorial,

secondly you have a small mistake,

please change the name of

File : res/layout/main.xml – WebView example

to be

File : res/layout/webview.xml – WebView example

im i right.?

Dan
Guest
Dan

I also was slightly confused by this and realized the error.

yusuf
Guest
yusuf

how to enable cookies in webview for android ?

yusuf
Guest
yusuf
just managed to do it WebView myWebView = (WebView) findViewById(R.id.wv1); myWebView.setWebViewClient(new WebViewClient(){ @Override public boolean shouldOverrideUrlLoading(WebView view, String url){ view.loadUrl(url); return true; } }); WebSettings webSettings = myWebView.getSettings(); webSettings.setJavaScriptEnabled(true); webSettings.setDomStorageEnabled(true); myWebView.loadUrl(“website url here/”);
Karsho
Guest
Karsho

Im new for this. Now I want to send push notification to my WebView App. Please, Can you explain like this?

Half Moon
Guest
Half Moon
????
Guest
????

hi I need use text in web view for ex. a story for reading thank u .

Nabaasa Gongo
Guest
Nabaasa Gongo

Thanks for the code…….it helped!

Murtaza Panhwar
Guest
Murtaza Panhwar

when i click on button it give me FC error guys help me out :(

Corent Sudibyo
Guest
Corent Sudibyo

hi if i wanna create login page using html and java as code, is it possible?how i send user id n pass from html to java, thx alot

manoj
Guest
manoj

I am following the same steps…but when i trying to export it automatically deletes the internet permession line…..and because of that…application doeant run….qhat should i do…why this is happening…?

Steve Ridwan
Guest
Steve Ridwan

hi, i’m new in android programming, i’m getting error when i create webViewActivity.java

the error is : webview cannot be resolved or is not a field, i try to create that field but not help

here is screen capture: http://postimg.org/image/bhvcqfh39/
i hope you can help me, thanks

Funny Games
Guest
Funny Games
polash
Guest
polash

nice tutorial.. (Y)

riday
Guest
riday

yeap

Srihari K
Guest
Srihari K

One word. Awesome!

Rejuvenated Horizons
Guest
Rejuvenated Horizons

Hi,

I need help with a large text string in string.xml but it shows only the first page but the rest of the text doesn’t show at all. Any tips? — ScrollView is not helping or maybe I am doing something wrong there. Help!

Paritosh
Guest
Paritosh

Thanks! Short and Sweet article…

shariq
Guest
shariq

Chek it man your code is not running. you skip one line here…

add this line in your code……

webView.setWebViewClient(new WebViewClient());

From
Guest
From

Right shariq ! I’ve done same thing to make the webview able to navigate properly !

certee
Guest
certee

Yes! The code would try to run the website in the device’s internet browser without this code. Thanks!

Mugiwara
Guest
Mugiwara

Thanks for the info

Shahmoon Shahzad
Guest
Shahmoon Shahzad

Super B :)

jgcoroleu
Guest
jgcoroleu

Hi, thanks for your tutorial. How i do for to hide status bar when i run my app?

juan
Guest
juan

is it possible to build a java web app such as this in android? how much do you think it would cost? thanks!

Diego
Guest
Diego

Mk Kong rocks!

Diego
Guest
Diego

Mk Yong* :)

Arun Prabhu
Guest
Arun Prabhu

Thank you….

Mahesh sharma
Guest
Mahesh sharma

Perfect Example Thanks

Sanmoy Ray
Guest
Sanmoy Ray

The new webview is a mess (in kitkat). html5 canvas is not hardware accelerated and rendering performance is extremely poor. All games/apps which rely on canvas rendering are slowed down to death. There are multiple bugs raised, but google is completely silent on this mishap.

slow canvas bug :
1. https://code.google.com/p/chromium/issues/detail?id=315111
2. https://code.google.com/p/chromium/issues/detail?id=239864

slow css transformation :
https://code.google.com/p/chromium/issues/detail?id=329108

other issues :
https://code.google.com/p/android/issues/detail?id=62378 (text wrap bug)
https://code.google.com/p/android/issues/detail?id=62220 (broken filechooser)

The problems are so severe that developers are crying foul and asking the old webview back
https://code.google.com/p/android/issues/detail?id=62293

DJW
Guest
DJW

Hi I am having a problem with this line in MainActivity class

setContentView(R.layout.main);

the R class does not define main?
Any clues?

Kira00
Guest
Kira00

You need to create a layout file called main in your layout folder (res/layout/main.xml)

Gil Motta
Guest
Gil Motta

Thank you man! Great tutorial!

Shen Heng
Guest
Shen Heng
José
Guest
José
Hello, Thanks for the tutorial. Based on it I have built a small app that fills user and password on a form that is loaded in the webview, I got it working until I tried to add unsuccessfully a DownloadManager to download attachments. It’s not working now on the phone but oddly eclipse Emulator does work. Here is my code: Main activity import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class MainActivity extends Activity { private EditText user; private EditText pass; private Button button; public void onCreate(Bundle savedInstanceState) { final Context… Read more »
Ashish Ani
Guest
Ashish Ani

You can use the following web browser……….
https://www.andapponline.com/android/application/surfen-mini-w

Swap
Guest
Swap

Does it mean we can get the the web app directly on a mobile app.