How to open a webpage or a HTML fragment in your application

Today we have an example application that shows how to use Android WebView component. Our application displays a welcome screen with two buttons. The first one, when clicked, displays a screen which loads a web page in the application. The second one, when clicked, displays a HTML page fragment, a div with text and link (the a tag) element, which is being build in the application. When you click on the link element that is displayed it will open a build in Android browser and take you to the web page. Our Android WebView example application looks like this.

Android WebView Example

Android WebView Example

Our project structure looks like this.

Android WebView Example - Eclipse project structure

Android WebView Example – Eclipse project structure

These are our codes.

AndroidManifest.xml

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />
    <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.itcuties.android.apps.itcwebviewexample.ButtonsActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.itcuties.android.apps.itcwebviewexample.LocalActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.itcuties.android.apps.itcwebviewexample.URLActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
            </intent-filter>
        </activity>
    </application>

</manifest>

This is our example descriptor. We specify three application activities here and a the android.permission.INTERNET permission.

activity_buttons.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"
    tools:context=".ButtonsActivity" >

    <Button
        android:id="@+id/localButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/urlButton"
        android:layout_below="@+id/urlButton"
        android:layout_marginTop="20dp"
        android:text="Local content" />

    <Button
        android:id="@+id/urlButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="142dp"
        android:text="URL content" />

</RelativeLayout>

This code is the layout of the screen that displays buttons. We specify two Button components here, one for displaying the web page and the second one for displaying the locally build content. When the screen renders it will look pretty much like this.

Android WebView Example - activity-buttons layout

Android WebView Example – activity-buttons layout

activity_webview.xml

<?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/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

This is the layout where our content is displayed. We use the same layout to display the webpage loaded from the URL and locally build page fragment. TextView component is for displaying some title of the screen and the WebView component is for displaying the content.

Android WebView Example - activity-webview layout

Android WebView Example – activity-webview layout

ButtonsActivity.java

package com.itcuties.android.apps.itcwebviewexample;

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

public class ButtonsActivity extends Activity implements OnClickListener {

	private Button urlButton;
	private Button localButton;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_buttons);
		
		urlButton 	= (Button)findViewById(R.id.urlButton);
		localButton	= (Button)findViewById(R.id.localButton);
		
		urlButton.setOnClickListener(this);
		localButton.setOnClickListener(this);
		
	}

	@Override
	public void onClick(View v) {
		if (urlButton.isPressed()) {
			Intent i = new Intent(this, URLActivity.class);
			this.startActivity(i);
			
		} else if (localButton.isPressed()) {
			Intent i = new Intent(this, LocalActivity.class);
			this.startActivity(i);
		}
	}
}

This activity is a simple one. Content view is set to the activity_buttons layout. Next, we find our button references and set them the OnClickListener to this object. This class implements OnClickListener interface and provides the implementation of the onClick method where we start URLActivity or LocalActivity depending on the button clicked.

URLActivity.java

package com.itcuties.android.apps.itcwebviewexample;

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

public class URLActivity extends Activity {

	@SuppressLint("SetJavaScriptEnabled")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_webview);
		
		WebView webView = (WebView)findViewById(R.id.webView);

		webView.setInitialScale(1);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.getSettings().setLoadWithOverviewMode(true);
		webView.getSettings().setUseWideViewPort(true);
		webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
		webView.setScrollbarFadingEnabled(false);
		
		webView.loadUrl("http://www.itcuties.com");
		
	}	
}

In this activity we load a webpage by calling the WebView.loadUrl method. But before we do that we set some preferences. The JavaScript support is enabled by calling webView.getSettings().setJavaScriptEnabled(true);. Next we tell the WebView to load the page in the overview mode by writing this webView.getSettings().setLoadWithOverviewMode(true);. Next the wide viewport is set – webView.getSettings().setUseWideViewPort(true);. At the end we set the scrollbar to appear at the edge of the view – webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);. Lastly we tell the scrollbar not to fade when it is not used – webView.setScrollbarFadingEnabled(false);.

LocalActivity.java

package com.itcuties.android.apps.itcwebviewexample;

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

public class LocalActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_webview);
		
		StringBuffer data = new StringBuffer();
		data.append("<div>");
		data.append("This is a local text that was set in the application.");
		data.append("<br/>");
		data.append("<a href='http://www.itcuties.com'>Visit itcuties.com</a>");
		data.append("</div>");
		
		WebView webView = (WebView)findViewById(R.id.webView);
		webView.loadData(data.toString(), "text/html", "UTF-8");
	}	
}

In this activity code we build a HTML fragment using a StringBuffer object. Our sample fragment contains a div, some text and a a tag. To display this data just call the WebView.loadData method providing it the content, its mime type and encoding.

Download this sample code here.

Install this application from here.

This code is available on our GitHub repository as well.

7 Responses to "How to open a webpage or a HTML fragment in your application"

  1. Abdur Rehman says:

    It will me more nice to use fragment in it means in left it have content such as in left it show android,java,wordpress etc buttons or links in right it show this link or button data in same layout and its possible by using fragment

    Reply
  2. rupak says:

    all links clicked on webview are opening on browser.

    how to make it open in the app?
    Any way to show progress bar?

    thanks

    Reply
  3. deepak pandey says:

    how t to play video with webview this code have no play video online

    Reply
  4. anjali says:

    how to link the rss feed for three url’s to three different buttons in an application?

    Reply

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply to anjali Cancel 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> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>