每次点击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);
}
答案 0 :(得分:5)
试试这个:
@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();
}
}
答案 1 :(得分:1)
我可以在您的代码中发现一些问题。
请勿从WebView.loadUrl
致电shouldOverrideUrlLoading
。它不是必需的,实际上创建了一个循环。负载已在进行中。
请显示onPageStarted
回调中的对话框,并将其从onPageFinished
中删除(与您现在一样)。 onLoadResource
和onShouldOverrideUrlLoading
不适合展示您正在寻找的效果。
希望这有帮助!