4

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);
}
Dan Hastings
  • 3,241
  • 7
  • 34
  • 71
  • 2
    Possible duplicate of [How to handle back button in activity](http://stackoverflow.com/questions/5312334/how-to-handle-back-button-in-activity) – Jonas Köritz Jun 07 '16 at 07:55
  • 1
    Possible duplicate of [How to go back to previous page if back button is pressed in WebView?](https://stackoverflow.com/q/6077141/6521116) – LF00 Jun 23 '17 at 04:17

4 Answers4

20

I think you should override your activity OnBackPressed :

@Override
public void onBackPressed() {
    if (webView.canGoBack()) {
        webView.goBack();
    } else {
        super.onBackPressed();
    }
}
Kingfisher Phuoc
  • 8,052
  • 9
  • 46
  • 86
3

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();
    }
}
Wesley
  • 4,084
  • 6
  • 37
  • 60
0

Full reference for next button and progress bar : put back and next button in webview

If you want to go to back page when click on phone's back button, use this:

@Override
public void onBackPressed() {
    if (webView.canGoBack()) {
        webView.goBack();
    } else {
        super.onBackPressed();
    }
} 

You can also create custom back button like this:

btnback.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            if (wv.canGoBack()) {
                wv.goBack();
            }
        }
    }); 
Parsania Hardik
  • 4,593
  • 1
  • 33
  • 33
0

Backkey pressed event is not suitable here use this code:

@Override
public void onBackPressed() {
    super.onBackPressed();
    Intent intent=new Intent(LiveImage.this,DashBoard.class);
    startActivity(intent);
}
Pradeep Kumar
  • 2,349
  • 1
  • 10
  • 18