Thursday, July 8, 2010

Android: Showing indeterminate progress bar / TabHost activity setProgressBarIndeterminateVisibility

Code is pretty simple. request the feature , toggle the Visibility.

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;

public class DemoActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        Button b =new Button(this);
        b.setText("Click to start spinning");
        b.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                DemoActivity.this.setProgressBarIndeterminateVisibility(true);
            }});
        Button c =new Button(this);
        c.setText("Click to STOP spinning");
        c.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                DemoActivity.this.setProgressBarIndeterminateVisibility(false);
            }});
        LinearLayout l=new LinearLayout(this);
        l.addView(b);
        l.addView(c);
        this.setContentView(l);
    }
}

image

if you use a TabActivity as a parent, and your logical activity is a child of the parent. you need request the feature in the onCreate method of TabActivity.

in your logical activity, call the getparent to get the access of the parentactivity reference.

So code will be

Parent(TabActivitity)
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

your child activity
((taballActivity)this.getParent()).setProgressBarIndeterminateVisibility(true);

if your logic runing in a different thread other than Main ui thread.

ChildActivity.this.runOnUiThread(
                            new Runnable()
                            {

                                public void run() {
                                    // TODO Auto-generated method stub
                                    ((taballActivity)ChildActivity.this.getParent()).setProgressBarIndeterminateVisibility(false);
                                }

                            }
                    );


 
Locations of visitors to this page