Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Webview make back button go to previous page

Tags:

android

I have a web view that lets me browse through a site. When i click the back button, rather than it going to the previous page it exits the app. I have added the following method to MainActivity.java

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    setContentView(R.layout.activity_main);
    WebView webview = (WebView) this.findViewById(R.id.webView);
    if (event.getAction() == KeyEvent.ACTION_DOWN) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (webview.canGoBack()) {
                    webview.goBack();
                } else {
                    finish();
                }
                return true;
        }
    }
    return super.onKeyDown(keyCode, event);
}
like image 328
Dan Hastings Avatar asked Sep 02 '25 09:09

Dan Hastings


2 Answers

I think you should override your activity OnBackPressed :

@Override
public void onBackPressed() {
    if (webView.canGoBack()) {
        webView.goBack();
    } else {
        super.onBackPressed();
    }
}
like image 86
Kingfisher Phuoc Avatar answered Sep 04 '25 23:09

Kingfisher Phuoc


Do not override onKeyDown event, override onBackPressed, so that every time the back button is pressed, you can override it and add your own logic into it. The Code is like this:

@Override
public void onBackPressed() {
    if (webView.canGoBack()) {
        webView.goBack();
    } else {
        super.onBackPressed();
    }
}
like image 44
Wesley Avatar answered Sep 05 '25 00:09

Wesley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!