How to control the Android WebView history/back stack?

后端 未结 7 1977
半阙折子戏
半阙折子戏 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:00

    boolean isGoBack = false;    //back key is pressed
    
    private long goBackTime = 0; //
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
            isGoBack = true;
            goBackTime = System.currentTimeMillis();
            mWebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    
    Webview mWebView.
    
    setWebViewClient(new WebViewClient() { //setWebViewClient
        @Override
        public boolean shouldOverrideUrlLoading (WebView view, String url){
            if (!TextUtils.isEmpty(startUrl) && !startUrl.equals(url) && isGoBack && System.currentTimeMillis() - goBackTime < 600) {
                isGoBack = false;
                if (mWebView.canGoBack()) {
                    mWebView.goBack();
                } else {
                    finish(); //activity finish
                }
            } else {
                view.loadUrl(url);
                isGoBack = false;
                return true;
            }
    
            return false;
        }
        @Override
        public void onPageStarted (WebView view, String url, Bitmap favicon){
            super.onPageStarted(view, url, favicon);
    
            startUrl = url;
        }
    }
    

提交回复
热议问题