如何在webview中成功加载网页时触发功能?

时间:2012-11-14 11:21:12

标签: android webview

我希望在webview完成加载网页并且没有收到任何错误后触发一个功能。根据我的实验,onPageFinished()将被触发多次,在大多数情况下,它将在onReceivedError()之前执行。

那么我怎么知道网页已加载且没有收到错误?

1 个答案:

答案 0 :(得分:3)

您可以在WebViewClient中设置WebView并覆盖其回拨方法,以便在网页加载完页面时通知您。例如

webView.setWebViewClient(new MyWebViewClient());


private class MyWebViewClient extends WebViewClient {


    @Override
    public void  onPageStarted(WebView view, String url, Bitmap favicon){
        super.onPageStarted(view, url, favicon);
        if(progess!=null){
            progess.dismiss();

        }
        progess = ProgressDialog.show(LoadUrl.this, "", "Loading please wait...");
    }
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        super.shouldOverrideUrlLoading(view, url);
        if (Uri.parse(url).getHost().equals("callback")) {
            // This is my web site, so do not override; let my WebView load the page
             Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
            return false;
        }
        // Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs

        view.loadUrl(url);
       return true;
    }

    @Override
    public void onPageFinished(WebView view, String url){
        super.onPageFinished(view, url);

        // Add YOUR CODE HERE 
    }

    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
     super.onReceivedError(view, errorCode, description, failingUrl);
     Toast.makeText(LoadUrl.this, "Sorry! " + description, Toast.LENGTH_SHORT).show();
   }

    @Override
 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
     super.onReceivedSslError(view, handler, error);
     handler.proceed(); 


 }
}

当webView加载完当前页面时,将调用此onPageFinished(WebView view, String url)

希望有所帮助:)