71

I have looked at a question similar to this here but as I am a newbie could someone explain how to get this to work in a WebView or at least how to set a 10 second time delay so people know that it's loading?

Community
  • 1
  • 1
Max Marroni
  • 937
  • 1
  • 7
  • 7
  • 1
    This an almost exact duplicate of http://stackoverflow.com/questions/2496119/in-an-android-app-i-would-like-to-show-a-progress-bar-on-a-child-tab-until-the-we/2496273#2496273. Have a look over there to see if that helps. If it doesn't, edit your question to provide details of what exactly you aren't managing to get to work. – Steve Haley Mar 29 '10 at 11:30
  • 1
    You've got the full code to make a progress loading bar available in the link to the Android Developers' site. Have you even tried to use their example? Once you have, you should be able to adapt it to your needs. – Steve Haley Mar 29 '10 at 12:12
  • How do I do the same thing in a fragment? I am following the same steps but the progress bar ins't visible. – praxmon Jan 19 '16 at 08:30

8 Answers8

145

For a horizontal progress bar, you first need to define your progress bar and link it with your XML file like this, in the onCreate:

final TextView txtview = (TextView)findViewById(R.id.tV1);
final ProgressBar pbar = (ProgressBar) findViewById(R.id.pB1);

Then, you may use onProgressChanged Method in your WebChromeClient:

MyView.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {
               if(progress < 100 && pbar.getVisibility() == ProgressBar.GONE){
                   pbar.setVisibility(ProgressBar.VISIBLE);
                   txtview.setVisibility(View.VISIBLE);
               }

               pbar.setProgress(progress);
               if(progress == 100) {
                   pbar.setVisibility(ProgressBar.GONE);
                   txtview.setVisibility(View.GONE);
               }
            }
        });

After that, in your layout you have something like this

<TextView android:text="Loading, . . ." 
    android:textAppearance="?android:attr/textAppearanceSmall"
    android:id="@+id/tV1" android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:textColor="#000000"></TextView>

<ProgressBar android:id="@+id/pB1"
    style="?android:attr/progressBarStyleHorizontal" android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:layout_centerVertical="true"
    android:padding="2dip">
</ProgressBar>

This is how I did it in my app.

rogerdpack
  • 62,887
  • 36
  • 269
  • 388
Yahyaotaif
  • 1,943
  • 1
  • 15
  • 17
  • 3
    This should be marked as the best answer since it's up-to-date in terms of deprecated code in the code snippets of the WebView docs (https://developer.android.com/reference/android/webkit/WebView.html) – DaveNOTDavid Jun 27 '17 at 22:16
21

I have just found a really good example of how to do this here: http://developer.android.com/reference/android/webkit/WebView.html . You just need to change the setprogress from:

activity.setProgress(progress * 1000);

to

activity.setProgress(progress * 100);
Max Marroni
  • 937
  • 1
  • 7
  • 7
10

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 :)

Md. Sajedul Karim
  • 6,749
  • 3
  • 61
  • 87
  • 1
    Thanks. I deleted `shouldOverrideUrlLoading` and `onLoadResource`, moved a progress start to `onPageStarted`. Also added `onReceivedError` and wrote there a progress end and toast message. – CoolMind Oct 25 '16 at 09:26
10

According to Md. Sajedul Karim answer I wrote a similar one.

webView = (WebView) view.findViewById(R.id.web);
progressBar = (ProgressBar) view.findViewById(R.id.progress);
webView.setWebChromeClient(new WebChromeClient());

setProgressBarVisibility(View.VISIBLE);
webView.setWebViewClient(new WebViewClient() {
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        setProgressBarVisibility(View.VISIBLE);
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        setProgressBarVisibility(View.GONE);
    }

    @Override
    public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
        super.onReceivedError(view, request, error);
        Toast.makeText(getActivity(), "Cannot load page", Toast.LENGTH_SHORT).show();
        setProgressBarVisibility(View.GONE);
    }
});

webView.loadUrl(url);

private void setProgressBarVisibility(int visibility) {
    // If a user returns back, a NPE may occur if WebView is still loading a page and then tries to hide a ProgressBar.
    if (progressBar != null) {
        progressBar.setVisibility(visibility);
    }
}
CoolMind
  • 26,736
  • 15
  • 188
  • 224
5

It's true, there are also more complete option, like changing the name of the app for a sentence you want. Check this tutorial it can help:

http://www.firstdroid.com/2010/08/04/adding-progress-bar-on-webview-android-tutorials/

In that tutorial you have a complete example how to use the progressbar in a webview app.

Adrian.

3

This is how I did it with Kotlin to show progress with percentage.

My fragment layout.

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
         xmlns:tools="http://schemas.android.com/tools"
         android:layout_width="match_parent"
         android:layout_height="match_parent">

<WebView
    android:id="@+id/webView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

<ProgressBar
    android:layout_marginLeft="32dp"
    android:layout_marginRight="32dp"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:id="@+id/progressBar"/>
</FrameLayout>

My kotlin fragment in onViewCreated

    progressBar.max = 100;
    webView.webChromeClient = object : WebChromeClient() {
        override fun onProgressChanged(view: WebView?, newProgress: Int) {
            super.onProgressChanged(view, newProgress)
            progressBar.progress = newProgress;
        }
    }

    webView!!.webViewClient = object : WebViewClient() {

        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            progressBar.visibility = View.VISIBLE
            progressBar.progress = 0;
            super.onPageStarted(view, url, favicon)
        }

        override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
            view?.loadUrl(url)
            return true
        }

        override fun shouldOverrideUrlLoading(
            view: WebView?,
            request: WebResourceRequest?): Boolean {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                view?.loadUrl(request?.url.toString())
            }
            return true
        }

        override fun onPageFinished(view: WebView?, url: String?) {
            super.onPageFinished(view, url)
            progressBar.visibility = View.GONE
        }
    }

    webView.loadUrl(url)
ninjahoahong
  • 2,624
  • 22
  • 20
0

You may looking for progress bar that most browser use...

My XML:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">
    <LinearLayout
        android:id="@+id/progressLayout"
        android:layout_width="match_parent"
        android:layout_height="5dp"
        android:background="#3F51B5"
        android:orientation="horizontal">
        <ProgressBar
            android:id="@+id/progressbar"
            android:layout_width="match_parent"
            android:layout_height="5dp"
            android:background="#3F51B5"
            android:indeterminate="false"
            style="?android:progressBarStyleHorizontal" />
    </LinearLayout>
    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

Inside onCreate:

webview.loadUrl("https://www.google.com");

The core:

    webview.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageStarted(WebView _param1, String _param2, Bitmap _param3) {
            everyTime = new TimerTask() {
                @Override
                public void run() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            progressbar.setProgress(webview.getProgress());
                        }
                    });
                }
            };
            _timer.scheduleAtFixedRate(everyTime, (int)(1), (int)(1));
            //This code below is optional
            progressbar.setVisibility(View.VISIBLE);
            //
            super.onPageStarted(_param1, _param2, _param3);
        }
        
        @Override
        public void onPageFinished(WebView _param1, String _param2) {
            progressLayout.setVisibility(View.INVISIBLE);
            everyTime.cancel();
            super.onPageFinished(_param1, _param2);
        }
    });

No problem if you replace WebViewClient with ChromeClient ;)

Output: Progress bar shown while load an webview.

-3

wait until the process is over ...

while(webview.getProgress()< 100){}
progressBar.setVisibility(View.GONE);
Jens Erat
  • 37,523
  • 16
  • 80
  • 96
idan
  • 1,508
  • 5
  • 29
  • 60