ProgressDialog Demo

This demo shows how to use ProgressDialog in the horizontal style. You can add your own task while the progress bar is displaying. This will also show how to update the progress bar as you are doing your task. For the sake of simplicity of source code I do not create onClickListener. Instead I use the “andoroid.onClick” property of a button.

In the layout xml, add a button and change onClick property with “startProgress” that we will be implementing in a moment.

[code language=”xml”]
<Button
android:id="@+id/btnStartProgress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="startProgress"
android:text="@string/start_progress" />
[/code]

Here is the full source code.

[code language=”java”]
package edu.kettering.progressbardemo;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;

public class ProgressBarDemo extends Activity {
final static int maxValue = 500;
private ProgressDialog progressBar;
private int progress;
private int progressSomthing;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_progress_bar_demo);
}

public void startProgress(View v) {
progressBar = new ProgressDialog(v.getContext());
progressBar.setCancelable(true);
progressBar.setMessage("Wait…");
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressBar.setProgress(0);
progressBar.setMax(maxValue);
progressBar.show();

progress = 0;
progressSomthing = 0;

// make a runnable to be used in the thread
Runnable runProgress = new Runnable() {
public void run() {
while (progress < maxValue) {

progress = doSomething();

progressBar.setProgress(progress);
}

if (progress >= maxValue) {
progressBar.dismiss();
}
}
};

Thread thread = new Thread(runProgress);
thread.start();
}

// this should return a progress value
public int doSomething() {
// sleep 50 millisecond
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
progressSomthing++;

return progressSomthing;
}
}
[/code]

Leave a Reply

Your email address will not be published. Required fields are marked *