here is the easiest way to add progress bar in android Web View.
Add a boolean field in your activity/fragment
private boolean isRedirected;
This boolean will prevent redirection of web pages cause of dead links.Now you can just pass your WebView object and web Url into this method.
private void startWebView(WebView webView,String url) {
webView.setWebViewClient(new WebViewClient() {
ProgressDialog progressDialog;
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
isRedirected = true;
return false;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
isRedirected = false;
}
public void onLoadResource (WebView view, String url) {
if (!isRedirected) {
if (progressDialog == null) {
progressDialog = new ProgressDialog(SponceredDetailsActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
}
}
public void onPageFinished(WebView view, String url) {
try{
isRedirected=true;
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
}catch(Exception exception){
exception.printStackTrace();
}
}
});
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
}
Here when start loading it will call onPageStarted
. Here i setting Boolean field is false. But when page load finish it will come to onPageFinished
method and here Boolean field is set to true. Sometimes if url is dead it will redirected and it will come to onLoadResource()
before onPageFinished
method. For this reason it will not hiding the progress bar. To prevent this i am checking if (!isRedirected)
in onLoadResource()
in onPageFinished()
method before dismissing the Progress Dialog you can write your 10 second time delay code
That's it. Happy coding :)