我想在 webview 完成加载网页并且没有收到错误后触发一个函数。根据我的实验,onPageFinished() 会被多次触发,并且在大多数情况下,它会在 onReceivedError() 之前执行。
那么如何才能知道网页加载完毕并且没有收到错误呢?
您可以设置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();
}
}
这里onPageFinished(WebView view, String url)
会在 webView 加载完当前 Page 时调用。
希望能帮助到你 :)