Thursday, September 6, 2018

How to go back to previous page if back button is pressed in WebView?


Credit goes to StackOverFlow

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (event.getAction() == KeyEvent.ACTION_DOWN) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (mWebView.canGoBack()) {
                    mWebView.goBack();
                } else {
                    finish();
                }
                return true;
        }

    }
    return super.onKeyDown(keyCode, event);
}
 
 
=======================
 
For this code to work, you need to add a field to the Activity containing the WebView:
private WebView mWebView; Initialize it in the onCreate() method and you should be good to go.
mWebView = (WebView) findViewById(R.id.webView);
 

No comments:

Post a Comment