4

I'm trying to instantiate a Progress Bar from the main Activity and add it to the view dynamically. When I do this, I get a bar:

ProgressBar bar = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
bar.setLayoutParams(params);
bar.setId(mInt);
LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
layout.addView(bar);

I started a new project that only includes the above code, and the progress bar displays correctly.

If I add the following lines to the above code, the screen is blank for a second and then shows a half full bar. I would expect to see an empty bar for a second and then it goes to 50%.

try {
    Thread.sleep(2000);
} catch ...{
}
bar.setProgress(50);

If I add some code like this, however, the bar and changes display correctly.

Button b = new Button(this);
        b.setText("change bar");
        b.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                changeProg();
            }
        });

public void changeProg() {
        switch (state) {
        case 0: bar.setProgress(100); state = 1; break;

        case 1: bar.setProgress(127); state = 2; break;

        case 2: bar.setProgress(33);  state = 0; break;
        }
    }

If I try to automate the process with a loop to call changeProg() every so often, the screen just stays blank - no widgets at all display, whether they are described by the XML or pro grammatically makes no difference.

I'm having trouble understanding why this behavior exists.

nexus_2006
  • 744
  • 2
  • 14
  • 29

4 Answers4

1

It seems that you call Thread.sleep(2000) from UI thread, which causes the problem, even create ANR. Try to create a new thread (separate thread) to change the progress value.

See the example below:

https://stackoverflow.com/a/17758416/3922207

Community
  • 1
  • 1
Anggrayudi H
  • 14,977
  • 11
  • 54
  • 87
1
ProgressBar pdialog = new ProgressBar(context,null, android.R.attr.yourcustomstyle);

and check your apptheme in style

Ajay Venugopal
  • 1,544
  • 1
  • 17
  • 30
0

SetProgress tip:

Set the current progress to the specified value. Does not do anything if the progress bar is in indeterminate mode.

So you have to call:

bar.setIndeterminate(false);

-3

Have you tried looking at this site?

http://www.mkyong.com/android/android-progress-bar-example/

The correct way is use 1 thread to run your time consuming task and another thread to update the progress bar status

Hope this helps!

aandroidtest
  • 1,493
  • 8
  • 41
  • 68