1)Create a simple HelloAndroid application in Eclipse using ADT plugin.
2)Open the
res/layout/main.xml
file and replace the code with the below snippet :< ? xml version="1.0" encoding="utf-8"? >
< WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/ >
3)Now update
HelloWebView.java
file as below in the onCreate() method,WebView mWebView;This will update the view with a Webview widget.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("http://www.google.com");
}
4)Because this application needs access to the Internet, you need to add the appropriate permissions to the Android manifest file. Hence include the below tag in the AndroidManifest.xml file before the Application tag;
< uses-permission android:name="android.permission.INTERNET" / >5)remove the title bar, with the "NoTitleBar" theme bu including the below attribute in the activity tag
android:theme="@android:style/Theme.NoTitleBar"6)Now add the below class as a nested class within the Activity class,
private class HelloWebViewClient extends WebViewClient {7)Set the instance of the above nested class from witing the onCreate() method as below:
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
mWebView.setWebViewClient(new HelloWebViewClient());
8)To handle the BACK button key press on the device, add the following method inside the
HelloWebView
Activity:@OverrideNow run your application ...
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}