Android WebView Tutorial

The WebView enables you to embed a web browser in your activity. It is very useful to display some online/offline web contents within your activity.  It uses the WebKit rendering engine to display web pages.

Step 1: Setting up the project


First create new Android SDK project in eclipse or your IDE of choice. You can name the main activity, package and project anything you want.

WebView Project Setup


Step 2: Setting up the WebView Widget


Open the layout file & then add a WebView, assign an ID so you can access the widget later.

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

</LinearLayout> 


Step 3: Requesting Internet Permission (Android Manifest) 


Since we’re going to load a URL in the WebView widget, we have to make sure to request permission to access the Internet in AndroidManifest.xml. Open AndroidManifest.xml file and declare a uses-permission element just above <application> ... </application> element.

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


Step 4: Loading a Web Page 


Open up your main activity and add the following code into the onCreate() method:

WebView mywebview = (WebView) findViewById(R.id.webview);
 mywebview.loadUrl("http://www.androidaspect.com/?m=1");

The above code accesses the WebView widget via its resource ID and invokes loadUrl() method. Start the app in the emulator and view the result: it should display the site you’re currently on!


Android WebView Example


Step 5: Enabling JavaScript


JavaScript is disabled in a WebView by default. You can enable it through the WebSettings attached to your WebView. You can retrieve WebSettings with getSettings(), then enable JavaScript with setJavaScriptEnabled().

WebSettings webSettings = mywebview.getSettings();
webSettings.setJavaScriptEnabled(true);

(Note: Add it just below the code in step 4)


Step 6: Built-in Zoom Controls


To display the built-in zoom controls, you need to first get the WebSettings property from the WebView & then call its setBuiltInZoomControls() method.

webSettings.setBuiltInZoomControls(true);

(Note: Add it just before the code in step 5)

Step 7: Handling Page Navigation


When you clicks a link from a web page in your WebView, it will cause your application to launch the browser application to load the desired page. However, you can override this behavior for your WebView, so links open within your WebView. You can then allow the user to navigate backward and forward through their web page history that's maintained by your WebView.

To open links clicked by the user, simply provide a WebViewClient for your WebView, using setWebViewClient().

mywebview.setWebViewClient(new WebViewClient());

That's it. Now all links the user clicks load in your WebView. If you want more control over where a clicked link load, create your own WebViewClient that overrides the shouldOverrideUrlLoading() method.

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

If you are going to create your own WebViewClient then you also need to assign it to your WebView as:

mywebview.setWebViewClient(new MyWebViewClient());


Step 8: Handling the Back Button Key Press


Whenever the user press the BACK button the activity that handles the WebView is closed. If you want to use BACK button to navigate from current opened link to previously opened link in WebView then you need to override the onKeyDown() inside the activity.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK) && mywebview.canGoBack()) {
        mywebview.goBack();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

The condition uses a KeyEvent to check whether the key pressed is the BACK button and whether the WebView is actually capable of navigating back (if it has a history). If both are not true, then it send the event up the chain (and the Activity will close). But if both are true, then it call goBack(), which will navigate back one step in the history. You can also navigate forward through the history with goForward() method.


Step 9: Rendering Custom Markup


You can also dynamically formulate an HTML string & load it into the WebView, using the loadData() method. It takes three arguments:
  1. String htmlData
  2. String mimeType
  3. String encoding
Comment out the mywebview.loadUrl() line and insert the following code:
String data = "<html>"  + 
              "<body><h1>Hello, Android Aspect!</h1></body>"  + 
              "</html>";
mywebview.loadData(data, "text/html", "UTF-8"); 

Now Restart the app in the emulator and view the result: you should see this:

Android WebView Demo

Alternatively, You can also create your own HTML file & save it in assets folder, you can also load it into the WebView using the loadUrl() method.

First create a "hello.html" file & save it into assets folder.

<Body bgcolor="Green">
<H1>Hello HTML</H1>
<font color="yellow">WebView Tutorial by Android Aspect</font>
</Body>

Comment out the mywebview.loadData() line and insert the following code:

mywebview.loadUrl("file:///android_asset/hello.html");

Now Restart the app in the emulator and view the result: you should see this:


Android WebView Screen





7 Comments:

Sanath Nandasiri said...

thank you very much.save my tiime

Jerald said...

Very useful for beginners. Thanks.

Jozef Kralik said...

Thank You Very Much

Muhammad Osman said...

Many thanks

Kaushal Fauzdar said...

This is one of the best tutorial available on web about WebView

wajim said...

Many thanks for this useful page, all the android topics I was looking for are on only 1 webpage. BRAVO!

Anonymous said...

very informative and helpful. thanks a bunch!

Post a Comment

Recent Posts

Site Stats

Our Apps

Get it on Google Play

©2012-2014 Android Aspect - All rights reserved | Powered by Blogger

Creative Commons License