activity_main.xml
<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="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
MainActivity.java
package com.example.webview;
import android.os.Bundle;
import android.app.Activity;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends Activity {
WebView ourwebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadWeb();
}
public void loadWeb() {
WebView webView = (WebView)findViewById(R.id.webview);
ourwebView=webView;
this.setTitle("Android Happenings");
ourwebView.setWebViewClient(new WebViewClient());
String url="http://androidhappenings.blogspot.com/";
ourwebView.canGoBack();
ourwebView.loadUrl(url);
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode==KeyEvent.KEYCODE_BACK && ourwebView.canGoBack()) {
ourwebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
As we can see in the above java code, the onKeyDown method checks for back presses and move our web view one page back in each back press whenever possible. Also make sure that you add internet permission in your manifest or it will display web page not found error.
<uses-permission android:name="android.permission.INTERNET" />
Great tutorial.it is very helpful.
ReplyDeleteandroid apps development