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

后端 未结 17 1109
迷失自我
迷失自我 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:45

    The first answer by FoamyGuy is correct but I have some additions; low reputations cannot allow me to do comments. If for some reasons your page fails to load, ensure that you set a flag to take note of the failure and then check it on the onBackPressed override. Otherwise your canGoBack() will be forever executed without heading to the actual back activity if it was there:

    //flag with class wide access 
    public boolean ploadFailFlag = false;
    
    //your error handling override
    @Override
    public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
        onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
        ploadFailFlag = true;       //note this change 
        .....
        .....
    }
    
    //finally to the answer to this question:
    @Override
    public void onBackPressed() {
        if(checkinWebView.canGoBack()){
            //if page load fails, go back for web view will not go back - no page to go to - yet overriding the super 
            if(ploadFailFlag){
                super.onBackPressed();
            }else {
                checkinWebView.goBack();
            }
        }else {
            Toast.makeText(getBaseContext(), "super:", Toast.LENGTH_LONG).show();
            super.onBackPressed();
        }
    }
    

提交回复
热议问题