0

I have added a progress bar on a webview. My problem is when the webview is loading a url and the progress bar shows progress and I hit back button, progress bar still keeps loading till it gets completed and shows up on the back page where it should not.

 ProgressBar progressBar = (ProgressBar) rootView.findViewById(R.id.progressBar);
 webView.setWebChromeClient(new CustomWebChromeClient(progressBar));
 private static class CustomWebChromeClient extends WebChromeClient {

    private static final int MAX_PROGRESS = 100;
    private final ProgressBar progressBar;

    public CustomWebChromeClient(ProgressBar webProgress) {
        progressBar = webProgress;
    }

    @Override
    public void onProgressChanged(WebView web, int newProgress) {
        boolean stillLoading = isStillLoading(newProgress);
        if (hasWebProgress()) {
            progressBar.setProgress(newProgress);
            progressBar.setVisibility(stillLoading ? View.VISIBLE : View.GONE);
        }
        super.onProgressChanged(web, newProgress);
    }

    private boolean isStillLoading(int newProgress) {
        return newProgress < MAX_PROGRESS;
    }

    private boolean hasWebProgress() {
        return progressBar != null;
    }
}

OnBackPressed, when I try to do

progressBar.setVisibility(View.GONE);

this does not work. I can see code hitting this line on a breakpoint. All this is happening in a fragment.

user3773337
  • 2,086
  • 4
  • 20
  • 29

2 Answers2

0

first, there is something wrong in your naming. Inside your WebChromeClient you declare

private final ProgressBar ProgressBar;

that means your instance has the name of the Class.

second, you should put your ProgressBar outside of the WebView in a Relative or LinearLayout together with the WebView. In the WebViewClient you also have to hide the ProgressBar on finish loading or failed loading.

Christian
  • 4,596
  • 1
  • 26
  • 33
  • name of the variable was a typo here in the code it is private final ProgressBar progressBar. About the other suggestion I do not see any such methods in the class WebChromeClient. I tried a method onUnhandledInputEvent() but that does not catch the back button event. – user3773337 Jun 02 '15 at 21:21
  • WebViewClient, not WebChromeClient! – Christian Jun 02 '15 at 23:44
0

Have you tried putting the webview initiation code into a worker thread like this?

new Thread(new Runnable() {
    public void run() {

        // webview initiation code

    }
}).start();

Here is how it solved my own problem & here are the docs.

Community
  • 1
  • 1
rockhammer
  • 957
  • 2
  • 13
  • 38