Friday, March 23, 2012

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


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

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.
?
Drag and copy the code
01
02
03
04
05
06
07
08
09
10
11
12
13
<?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
?
Drag and copy the code
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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);
              }
            });
       }
    }

No comments: