How to control the Android WebView history/back stack?

后端 未结 7 1972
半阙折子戏
半阙折子戏 2021-02-04 10:49

I am trying to figure out a way to handle the WebView back stack similar to how the Android web browser handles it when the back button is pressed from within my own app\'s WebV

7条回答
  •  清酒与你
    2021-02-04 11:04

    private class ArticleWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return false;
        }
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK)
        {
            WebView wv = (WebView)findViewById(R.id.web);
            if (wv.canGoBack())
            {
                wv.goBack();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }
    

    This shouldOverrideUrlLoading method should return false if you want to handle the link in your webview rather than system browser, and do not call view.loadUrl(url), your webview will load url automatically if you return false. The history will be not correct if you load url manually.

提交回复
热议问题