ProgressBar是一个用来表明操作进度情况的控件.
试想这样一种场景:当用户按下DownLoad按钮时,后台开始从网络下载音乐文件,使用ProgressBar来告知用户当前的下载情况。
【效果图】
【代码要点】
main.xml<?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" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <ProgressBar android:id="@+id/progressBar1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:visibility="gone"> </ProgressBar> <Button android:id="@+id/button1" android:text="DownLoad" android:layout_width="wrap_content" android:layout_height="wrap_content"> </Button> </LinearLayout>
ProgressBarTest.javapackage enleo.ProgressBarTest; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; public class ProgressBarTest extends Activity { private static int progress = 0; private ProgressBar mProgress; private int progressStatus = 0; private Handler mHandler = new Handler(); private Button btnDownLoad; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mProgress = (ProgressBar) findViewById(R.id.progressBar1); btnDownLoad = (Button) findViewById(R.id.button1); btnDownLoad.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub mProgress.setVisibility(View.VISIBLE); new Thread(new Runnable(){ @Override public void run() { // TODO Auto-generated method stub while (progressStatus < 10) { //比如doWork在做网络下载任务的话,返回progressStatus值来更新progressBar的进度。 progressStatus = doWork(); // Update the progress bar mHandler.post(new Runnable() { public void run() { mProgress.setProgress(progressStatus); } }); } //任务结束后,将progressBar隐藏 mHandler.post(new Runnable() { public void run() { mProgress.setVisibility(View.GONE); } }); } }).start(); } //模拟网络下载任务 private int doWork() { try { //---simulate doing some work--- Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } return ++progress; } }); } }
ProgressBar根据表现情况的不同也有对应的Style选择.通常对于不可计量的下载情况,我们通常用一天循环的圆圈动画来表示。而那些可以计量的下载情况,可以用进度条来表示。
【不可计量】
【可计量】
【代码要点】 进度条style <ProgressBar android:id="@+id/progressBar1" android:layout_width="wrap_content" android:layout_height="wrap_content" style="?android:attr/progressBarStyleHorizontal" android:visibility="gone"> </ProgressBar>

