我希望每次单击WebView中的任何链接时都会显示一个加载程序。
目前在application start
上仅显示我loader
。
使用以下代码
有时不知道每个加载器的时间都不会出现,不确定为什么会发生。
// Force links and redirects to open in the WebView instead of in a browser
mWebView.setWebViewClient(new WebViewClient() {
ProgressDialog progressDialog = null;
//If you will not use this method url links are opeen in new brower not in webview
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (progressDialog == null) {
// in standard case YourActivity.this
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
view.loadUrl(url);
return true;
}
//Show loader on url load
public void onLoadResource (WebView view, String url) {
if (progressDialog == null) {
// in standard case YourActivity.this
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
}
public void onPageFinished(WebView view, String url) {
try{
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
}
catch(Exception exception){
exception.printStackTrace();
}
}
//Show error page
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
mWebView.loadUrl("file:///android_asset/error.html");
}
});
// Javascript enabled on webview
mWebView.getSettings().setJavaScriptEnabled(true);
//Load url in webview
mWebView.loadUrl(url);
}
尝试以下方法:
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (progressDialog == null) {
// in standard case YourActivity.this
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
view.loadUrl(url);
return true;
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
try {
if (progressDialog .isShowing()) {
progressDialog .dismiss();
progressDialog = null;
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
@Override
public void onLoadResource (WebView view, String url) {
}
public void onPageStarted(WebView webView, String url, Bitmap favicon) {
super.onPageStarted(webView, url, favicon);
if (progressDialog == null) {
// in standard case YourActivity.this
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
}
我可以在您的代码中发现一些问题。
-
请不要从
shouldOverrideUrlLoading
调用WebView.loadUrl
。它不需要,实际上创建了一个循环。负载已经在进行中。 -
请从
onPageStarted
回调中显示对话框,然后将其从onPageFinished
中取消(就像您现在一样)。onLoadResource
和onShouldOverrideUrlLoading
不是您要寻找的效果的正确位置。
希望这会有所帮助!