How to listen for a WebView finishing loading a URL?

前端 未结 17 756
予麋鹿
予麋鹿 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:07

    thanks for the answers. It helped me, but I had to improve it a bit for my needs. I had several pagestarts and finishes so I added a timer which checks if atfer the pagefinish is started a new pagestart. Okay, bad explanation. See the code :)

    myWebView.setWebViewClient(new WebViewClient() {
            boolean loadingFinished = true;
            boolean redirect = false;
    
            long last_page_start;
            long now;
    
            // Load the url
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (!loadingFinished) {
                    redirect = true;
                }
    
                loadingFinished = false;
                view.loadUrl(url);
                return false;
            }
    
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                Log.i("p","pagestart");
                loadingFinished = false;
                last_page_start = System.nanoTime();
                show_splash();
            }
    
            // When finish loading page
            public void onPageFinished(WebView view, String url) {
                Log.i("p","pagefinish");
                if(!redirect){
                    loadingFinished = true;
                }
                //call remove_splash in 500 miSec
                if(loadingFinished && !redirect){
                    now = System.nanoTime();
                    new android.os.Handler().postDelayed(
                            new Runnable() {
                                public void run() {
                                    remove_splash();
                                }
                            },
                            500);
                } else{
                    redirect = false;
                }
            }
            private void show_splash() {
                if(myWebView.getVisibility() == View.VISIBLE) {
                    myWebView.setVisibility(View.GONE);
                    myWebView_splash.setVisibility(View.VISIBLE);
                }
            }
            //if a new "page start" was fired dont remove splash screen
            private void remove_splash() {
                if (last_page_start < now) {
                    myWebView.setVisibility(View.VISIBLE);
                    myWebView_splash.setVisibility(View.GONE);
                }
            }
    
    });
    

提交回复
热议问题