How to listen for a WebView finishing loading a URL?

前端 未结 17 773
予麋鹿
予麋鹿 2020-11-22 05:40

I have a WebView that is loading a page from the Internet. I want to show a ProgressBar until the loading is complete.

How do I listen for

17条回答
  •  忘了有多久
    2020-11-22 06:06

    Just to show progress bar, "onPageStarted" and "onPageFinished" methods are enough; but if you want to have an "is_loading" flag (along with page redirects, ...), this methods may executed with non-sequencing, like "onPageStarted > onPageStarted > onPageFinished > onPageFinished" queue.

    But with my short test (test it yourself.), "onProgressChanged" method values queue is "0-100 > 0-100 > 0-100 > ..."

    private boolean is_loading = false;
    
    webView.setWebChromeClient(new MyWebChromeClient(context));
    
    private final class MyWebChromeClient extends WebChromeClient{
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 0){
                is_loading = true;
            } else if (newProgress == 100){
                is_loading = false;
            }
            super.onProgressChanged(view, newProgress);
        }
    }
    

    Also set "is_loading = false" on activity close, if it is a static variable because activity can be finished before page finish.

提交回复
热议问题