Mega Code Archive

 
Categories / Android / UI
 

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>