ProgressBar Demo

According to Android API Guides, we should avoid ProgressDialog. Instead, using ProgressBar in the layout is recommended.

Her is my layout xml. You may use other than RelativeLayout if you do not like it.

[code language=”xml”]
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".ProgressBarDemo2Activity" >

<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
[/code]

After putting a ProgressBar into my layout, I create a Runnable object and a Thread. Call the thread with the runnable object that has my own overridden run() method.

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

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ProgressBar;

public class ProgressBarDemo2Activity extends Activity {
private ProgressBar mProgressBar;
private int mProgress = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_progress_bar_demo2);

mProgressBar = (ProgressBar)findViewById(R.id.progressBar);

Runnable runWork = new Runnable() {
@Override
public void run() {
while(mProgress < 100) {
mProgress = doWork();
mProgressBar.setProgress(mProgress);
}
}
};
Thread thread = new Thread(runWork);
thread.start();
}

private int doWork() {
// sleep 50 millisecond
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mProgress++;

return mProgress;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.progress_bar_demo2, menu);
return true;
}
}
[/code]