首页 > 解决方案 > 如何在 WebView.loadUrl() 方法上添加 onCompletionListener?

问题描述

WebView 现在正在显示,但在此之前会出现一个空白屏幕,这可能是由于加载了 url。

// webview to load url
webView.loadUrl("https://www.google.com/");

我想在 url 完全加载并且 webview 准备好显示内容时添加 onCompletionListener 。

标签: androidandroid-webview

解决方案


试试这个 我怎么知道我的 WebView 已加载 100%?

或者这个网址

https://android--code.blogspot.com/2016/03/android-detect-when-webview-finish.html

 // Set a WebViewClient for WebView
            mWebView.setWebViewClient(new WebViewClient(){
                @Override
                public void onPageStarted(WebView view, String url, Bitmap favicon){
                    // Page loading started
         }

                /*
                    public void onPageFinished (WebView view, String url)
                        Notify the host application that a page has finished loading. This
                        method is called only for main frame. When onPageFinished() is called,
                        the rendering picture may not be updated yet. To get the notification
                        for the new Picture, use onNewPicture(WebView, Picture).

                    Parameters
                        view WebView: The WebView that is initiating the callback.
                        url String: The url of the page.
                */
                @Override
                public void onPageFinished(WebView view, String url){
                    // Page loading finished
                    Toast.makeText(mContext,"Page Loaded.",Toast.LENGTH_SHORT).show();
                }
            });

            // Set a WebChromeClient for WebView
            // Another way to determine when page loading finish
            mWebView.setWebChromeClient(new WebChromeClient(){
                /*
                    public void onProgressChanged (WebView view, int newProgress)
                        Tell the host application the current progress of loading a page.

                    Parameters
                        view WebView: The WebView that initiated the callback.

                        newProgress int: Current page loading progress, represented by an
                            integer between 0 and 100.
                */
                public void onProgressChanged(WebView view, int newProgress){
                    mTextView.setText("Page loading : " + newProgress + "%");

                    if(newProgress == 100){
                        // Page loading finish
                        mTextView.setText("Page Loaded.");
                    }
                }
            });
            // Enable JavaScript
            mWebView.getSettings().setJavaScriptEnabled(true);

            // Load the url in the WebView
            mWebView.loadUrl(mURL);
        }

推荐阅读