Android开发之ProgressDialog进度对话框用法示例

  public class MainActivity extends Activity {

  final static int MAX_PROGRESS = 100;

  //虚拟 填充长度为100的数组

  private int[] data = new int[50];

  //记录进度对话框完成百分比

  int progressStatus = 0;

  int hasDta = 0;

  ProgressDialog progressDialog01,progressDialog02;

  private Button buttonDate;

  private Button buttonTime;

  //创建一个负责更新进度的Handler

  Handler mHandler = new Handler(){

  @Override

  public void handleMessage(Message msg) {

  //表明消息是本程序发送的

  if (msg.what == 0x111){

  progressDialog02.setProgress(progressStatus);

  }

  }

  };

  @Override

  protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setContentView(R.layout.activity_main);

  buttonDate = (Button) findViewById(R.id.dataBn);

  buttonTime = (Button) findViewById(R.id.timeBn);

  iniClick();//Binding the listeners for you program

  }

  public void showSpinner(View source){

  //用静态方法显示环形进度条

  ProgressDialog.show(this,"任务执行中","热内执行中 请等待...",false,true);

  }

  public void showIndeterminate(View source){

  progressDialog01 = new ProgressDialog(MainActivity.this);

  //设置对话框标题

  progressDialog01.setTitle("任务正在执行中");

  //设置对话框执行内容

  progressDialog01.setMessage("任务正在执行中敬请等待~~~");

  //设置对话框“取消” 按钮关闭

  progressDialog01.setCancelable(true);

  //设置对话框进度条风格

  progressDialog01.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

  //设置进度条是否显示进度

  progressDialog01.setIndeterminate(true);

  progressDialog01.show();

  }

  public void showProgress(View source){

  //将进度条完成重设为0

  progressStatus = 0;

  //重新开始填充数组

  hasDta = 0;

  progressDialog02 = new ProgressDialog(MainActivity.this);

  progressDialog02.setMax(MAX_PROGRESS);

  //设置对话框标题

  progressDialog02.setTitle("任务正在执行中");

  //设置对话框执行内容

  progressDialog02.setMessage("任务正在执行中敬请等待~~~");

  //设置对话框“取消” 按钮关闭

  progressDialog02.setCancelable(false);

  //设置对话框进度条风格

  progressDialog02.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

  //设置进度条是否显示进度

  progressDialog02.setIndeterminate(false);

  progressDialog02.show();

  new Thread(){//模拟耗时操作

  @Override

  public void run() {

  while (progressStatus < MAX_PROGRESS){

  //bar1获取完成工作的百分比

  progressStatus += (int) (Math.random()*15);

  try{

  Thread.sleep(1000);

  }catch (InterruptedException e){

  e.printStackTrace();

  }

  //更新ProgressBar

  mHandler.sendEmptyMessage(0x111);

  }

  //任务完成进度条关闭

  progressDialog02.dismiss();

  }

  }.start();

  }

  public void iniClick(){

  //set listener for your Date button

  buttonDate.setOnClickListener(new View.OnClickListener() {

  @Override

  public void onClick(View v) {

  showIndeterminate(MainActivity.this.getWindow().getDecorView());

  }

  });

  //set listener for your Time button

  buttonTime.setOnClickListener(new View.OnClickListener() {

  @Override

  public void onClick(View v) {

  showProgress(MainActivity.this.getWindow().getDecorView());

  }

  });

  }

  }