webView.canGoBack() not working anymore

落花浮王杯 提交于 2019-12-11 06:02:24

问题


Recently all of my WebView based apps started to have problem with back button. It looks an issue with update of some Android Component, Kindly help with the issue or some alternative solution?

webView.canGoBack() always returning false.

PS: All apps were working fine in previous days.

I'm using it like this:

   @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            super.onBackPressed();
        }
    }

回答1:


Create own canGoBack by like this....

ArrayList<String> urls = new ArrayList<>();
urls.add(www.google.com);

//after that you need override this method
 webView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            Log.d(TAG, "shouldOverrideUrlLoading: "+url);
            urls.add(url);
            return true;
        }
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) 
        {
            super.onPageStarted(view, url, favicon);
            pDialog.show();
        }
        @Override
        public void onPageFinished(WebView view, final String url) {
            pDialog.dismiss();
        }
    });

//for onBackPressed, same like in custom button for back click option
@Override
public void onBackPressed() {
    if(!canGoBack()
    {
       super.onBackPressed();
    }
}

//Custome Method
public boolean canGoBack()
{
    if(urls.size() == 1) // home page
    {
        return false;
    }
    else
    {
        webView.loadUrl(urls.get(urls.size()-2)); // load previous url
        urls.remove(urls.size()-1); // remove last loaded url
        return true;
    }
}


来源:https://stackoverflow.com/questions/47864253/webview-cangoback-not-working-anymore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!