How to show progress bar while loading a webpage in android?

By | November 3, 2011

This is a simple example showing how to load a webpage and show a progressBar while the page is loading in android.

For that you have to set a chrome client for the webview which implements “onProgressChanged”

Here is the layout file.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
  <WebView
    android:id="@+id/webview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
  </WebView>

</LinearLayout>

Here is the java file

package pack.coderzheaven;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;

public class LoadingWebViewDemo extends Activity {

	   WebView webview;
	   @Override
	   public void onCreate(Bundle savedInstanceState)
	   {
	      super.onCreate(savedInstanceState);

	      this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
	      setContentView(R.layout.main );

	      // Makes Progress bar Visible
	      getWindow().setFeatureInt( Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);

	       webview = (WebView) findViewById( R.id.webview );
	       webview.getSettings().setJavaScriptEnabled(true);
	       webview.getSettings().setSupportZoom(true);       //Zoom Control on web

	       webview.getSettings().setBuiltInZoomControls(true); //Enable Multitouch if supported by ROM

	       // Load URL
	       webview.loadUrl("http://www.google.com");

	       // This makes the Progress bar be updated.
	       final Activity MyActivity = this;
	       webview.setWebChromeClient(new WebChromeClient() {
	        public void onProgressChanged(WebView view, int progress)
	        {
	         MyActivity.setTitle("Loading...");
	         MyActivity.setProgress(progress * 100);

	         // Return the app name after finish loading
	            if(progress == 100)
	               MyActivity.setTitle(R.string.app_name);
	          }
	        });
	   }
	}

Leave a Reply

Your email address will not be published. Required fields are marked *