Tuesday, November 20, 2012

Simple Progress Dailog in android using Thread

In this tutorial we learn how to impliment progress dailog in android.

And also after complite progress bar handel the UI element using other Thread using Handler.


See below with example.

In this example my main activity XML is look like this.

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

    <Button
        android:id="@+id/start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Loading Dailog" />

    <TextView
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />

</LinearLayout>

JAVA file for this example is like this.

 private Button start;
 private ProgressDialog dailog;
 private TextView txt;
 Handler handler;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.abcd);

  start = (Button) findViewById(R.id.start);
  txt = (TextView) findViewById(R.id.txt);
  start.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {

    dailog = ProgressDialog.show(abcd.this, "Progress dailog sample ", "Loading please wait....", true);
    new Thread() {
     public void run() {
      try {
       // just doing some long operation
       sleep(5000);
      
      }
      catch (Exception e) {
      }
      handler.sendEmptyMessage(0);
      dailog.dismiss();
     }
    }.start();
   }
  });
  
   handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        txt.setText("Done");

    }
   };
 }
Enjoy.........


No comments:

Post a Comment