Android WebView Tutorial

Advertisements


WebView is a view that display web pages inside your application. You can also specify HTML string and can show it inside your application using WebView. WebView makes turns your application to a web application.

In order to add WebView to your application , you have to add <WebView> element to your xml layout file. Its syntax is as follows:

<WebView  xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/webview"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
/>

In order to use it, you have to get a refrence of this view in Java file. To get a reference , create an object of the class WebView. Its syntax is:

WebView browser = (WebView) findViewById(R.id.webview);

In order to load a web url into the WebView , you need to call a method loadUrl(String url) of the WebView class, specifying the required url. Its syntax is:

browser.loadUrl("http://www.tutorialspoint.com");

Apart from just loading url , you can have more control over your WebView by using the methods defined in WebView class. They are listed as follows:

Sr.NoMethod & Description
1canGoBack()
This method specify that wether the WebView has a back history item.
2canGoForward()
This method specify that wether the WebView has a forward history item.
3clearHistory()
This method will clear the WebView forwad and backward history.
4destroy()
This method destory the internal state of WebView.
5findAllAsync(String find)
This method find all instances of string and highlight them.
6getProgress()
This method gets the progress of the current page.
7getTitle()
This method return the title of the current page.
8getUrl()
This method return the url of the current page.

If you click on any link inside the webpage of the WebView , that page will not be loaded inside your WebView. In order to do that you need to extend your class from WebViewClient and override its method. Its syntax is:

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

Example

Here is an example demonstrating the use of WebView Layout. It creates a basic web application that will ask you to specify a url and will load this url website in the WebView.

To experiment with this example , you need to run this on an actual device on which intenet is running.

StepsDescription
1You will use Eclipse IDE to create an Android application and name it as WebView under a package com.example.webview. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2Modify src/MainActivity.java file to add WebView code.
3Modify the res/layout/activity_main to add respective XML components
4Modify the res/values/string.xml to add necessary string components
5Modify the AndroidManifest.xml to add the necessary permissions
6Run the application and choose a running android device and install the application on it and verify the results.

Following is the content of the modifed main activity file src/com.example.webview/MainActivity.java.

package com.example.webview;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

   private EditText field;
   private WebView browser;

   @Override		
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      field = (EditText)findViewById(R.id.urlField);
      browser = (WebView)findViewById(R.id.webView1);
      browser.setWebViewClient(new MyBrowser());
   }


   public void open(View view){
      String url = field.getText().toString();
      browser.getSettings().setLoadsImagesAutomatically(true);
      browser.getSettings().setJavaScriptEnabled(true);
      browser.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
      browser.loadUrl(url);

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

   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
   }

}

Following is the modified content of the xml res/layout/activity_main.xml.

<RelativeLayout 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: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" >

   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/hello_world" />

   <EditText
      android:id="@+id/urlField"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignTop="@+id/textView1"
      android:layout_centerHorizontal="true"
      android:ems="10" />

   <Button
      android:id="@+id/button1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_below="@+id/urlField"
      android:layout_centerHorizontal="true"
      android:onClick="open"
      android:text="@string/browse" />

   <WebView
      android:id="@+id/webView1"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_alignLeft="@+id/textView1"
      android:layout_alignParentBottom="true"
      android:layout_below="@+id/button1" />

</RelativeLayout>

Following is the content of the res/values/string.xml.

<?xml version="1.0" encoding="utf-8"?>
<resources>

   <string name="app_name">WebView</string>
   <string name="action_settings">Settings</string>
   <string name="hello_world">URL:</string>
   <string name="browse">Browse</string>

</resources>

Following is the content of AndroidManifest.xml file.

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

   <uses-sdk
      android:minSdkVersion="8"
      android:targetSdkVersion="17" />
   <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="com.example.webview.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>

Let's try to run your WebView application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Eclipse, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Before starting your application, Eclipse will display following window to select an option where you want to run your Android application.

Anroid WebView Tutorial

Select your mobile device as an option and then check your mobile device which will display your default screen:

Anroid WebView Tutorial

Now just specify a url on the url field and press the browse button that appears,to launch the website. But before that please make sure that you are connected to the internet. After pressing the button , the following screen would appear:

Anroid WebView Tutorial

Note. By just changing the url in the url field , your WebView will open your desired website.



Advertisements
Advertisements