Wednesday, 30 January 2013

Manage the Progress Bar | Android Tutorial pdf

Manage the Progress Bar

Finally, we need to actually make use of the progress indicator. This involves making it visible when we start our long-running task, updating it as the task proceeds, and hiding it again when the task is complete.
First, make it visible by updating onOptionsItemSelected() to show it:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==R.id.toast) {
String message="No restaurant selected";
if (current!=null) {
message=current.getNotes();
}
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
return(true);
}
else if (item.getItemId()==R.id.run) {
setProgressBarVisibility(true);
progress=0;
new Thread(longTask).start();
return(true);
}
return(super.onOptionsItemSelected(item));
}

Notice the extra line that makes progress visible.
Then, we need to update the progress bar on each pass, so make this change to doSomeLongWork():
private void doSomeLongWork(final int incr) {
runOnUiThread(new Runnable() {
public void run() {
progress+=incr;
setProgress(progress);
}
});
SystemClock.sleep(250); // should be something more useful!
}

Notice how we use runOnUiThread() to make sure our progress bar update occurs on the UI thread.
Finally, we need to hide the progress bar when we are done, so make this change to our longTask Runnable:
private Runnable longTask=new Runnable() {
public void run() {
for (int i=0;i<20;i++) {
doSomeLongWork(500);
}
runOnUiThread(new Runnable() {
public void run() {
setProgressBarVisibility(false);
}
});
}
};

At this point, you can rebuild, reinstall, and run the application. When you choose the Run Long T ask menu item, you will see the progress bar appear for five seconds, progressively updated as the "work" gets done:
                                                       The progress bar in action

No comments: