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

后端 未结 17 840
迷失自我
迷失自我 2020-11-22 07:06

I have an app in which I have a WebView where I display some websites. It works, clicking a link in the webpage goes to the next page in the website inside my a

17条回答
  •  礼貌的吻别
    2020-11-22 07:33

    I use something like this in my activities with WebViews:

    @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);
    }
    

    Edit:

    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);
    

提交回复
热议问题