Tuesday, March 11, 2014

Android Webview Example

Dear All,

In this example, we are going to see Android Webview. By using Webview we can load the HTML Application inside your android application.

Step 1 :

Create simple Android project in your Eclipse (Hello Word Android Project).

Step 2 :

Create "assets" folder in project Main directory.

Step 3 :

Copy & Paste your .html(dot html) file into the assets folder or create new html file inside your assets folder.

Step 4 : 

In this example , I have taken simple web example using jQuery Mobile UI. Copied html,javascript and css into the assets folder.

Step 5 :

Create Webview control in your main.xml.

updated 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=".WebviewActivity" >

    <WebView
        android:id="@+id/webView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" />

</RelativeLayout>

Step 6 : 

Modified MainActivity.java :

package com.seedev.webviewsample;

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

public class MainActivity extends Activity {
WebView myWebView;

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

//Find a view that was identified by the id attribute from XML.
myWebView = (WebView) findViewById(R.id.webView1);

//set the javascript enable true
myWebView.getSettings().setJavaScriptEnabled(true);

//Load the index.html file into the webview. 
myWebView.loadUrl("file:///android_asset/index.html");

}

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

Step 7 :

Now, Run the application in the Emulator/Device.

Download source code from Github.

No comments:

Post a Comment