Using Thread and Progress bar : Progress « UI « Android






Using Thread and Progress bar

   
package app.test;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ProgressBar;

public class Test extends Activity {

  private static int progress;
  private ProgressBar progressBar;
  private int progressStatus = 0;
  private Handler handler = new Handler();

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    progress = 0;
    progressBar = (ProgressBar) findViewById(R.id.progressbar);
    progressBar.setMax(200);

    new Thread(new Runnable() {
      public void run() {
        while (progressStatus < 200) {
          progressStatus = doSomeWork();
          handler.post(new Runnable() {
            public void run() {
              progressBar.setProgress(progressStatus);
            }
          });
        }
        handler.post(new Runnable() {
          public void run() {
            // ---0 - VISIBLE; 4 - INVISIBLE; 8 - GONE---
            progressBar.setVisibility(8);
          }
        });
      }

      private int doSomeWork() {
        try {
          // ---simulate doing some work---
          Thread.sleep(50);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        return ++progress;
      }
    }).start();
  }
}

//main.xml

<?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" >
    
 <ProgressBar android:id="@+id/progressbar"
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        style="?android:attr/progressBarStyleHorizontal" />
        
</LinearLayout>

   
    
    
  








Related examples in the same category

1.Using progress bar
2.Round ProgressBar vs Flat ProgressBar
3.Use progress bars as widgets and in the title bar. The progress bar in the title will be shown until the progress is complete, at which point it fades away.
4.Using indeterminate progress bars as widgets and in the window's title bar.
5.Use an indeterminate progress indicator in the window's title bar.
6.Progress Monitor