ProgressBar View
* The ProgressBar view provides visual feedback of some ongoing tasks, such as when you are per- forming a task in the background.
* For example, you might be downloading some data from the Web and need to update the user about the status of the download.
* In this case, the ProgressBar view is a good choice for this task.
1 . Using Eclipse, create an Android project and name it as ProgressBarView.
2 . Modify the main.xml file located in the res/layout folder by adding the following code in bold:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ProgressBar android:id="@+id/progressbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="?android:attr/progressBarStyleHorizontal" />
</LinearLayout>
3 . In the MainActivity.java file, add the following statements in bold:
package com.emergingandroidtech.ProgressBarView;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ProgressBar;
public class MainActivity extends Activity {
private static int progress;
private ProgressBar progressBar;
private int progressStatus = 0;
private Handler handler = new Handler();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
progress = 0;
progressBar = (ProgressBar) findViewById(R.id.progressbar);
progressBar.setMax(200);
//---do some work in background thread---
new Thread(new Runnable()
{
public void run()
{
//---do some work here---
while (progressStatus < 200)
{
progressStatus = doSomeWork();
//---Update the progress bar---
handler.post(new Runnable()
{
public void run() {
progressBar.setProgress(progressStatus);
}
});
}
//---hides the progress bar---
handler.post(new Runnable()
{
public void run()
{
//---0 - VISIBLE; 4 - INVISIBLE; 8 - GONE---
progressBar.setVisibility(8);
}
});
}
//---do some long lasting work here---
private int doSomeWork()
{
try {
//---simulate doing some work---
Thread.sleep(50);
} catch (InterruptedException e)
{
e.printStackTrace();
}
return ++progress;
}
}).start();
}
}
4 . It shows the ProgressBar animating. After about five seconds, it will disappear.
No comments:
Post a Comment