<LinearLayout 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:orientation="vertical"> <Button android:id="@+id/button2" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="环形进度条" android:onClick="showSpinner"/> <Button android:id="@+id/button1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="不显示进度的进度条" android:onClick="showIndeterminate" /> <Button android:id="@+id/button3" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="显示进度的进度条" android:onClick="showProgress" /> </LinearLayout>
package com.example.progressdialog; import android.app.Activity; import android.app.ProgressDialog; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; public class MainActivity extends Activity { final static int MAX_PROGRESS=100; private int[] data=new int [50]; int progressStatus=0; int hasData=0; ProgressDialog pd1,pd2; //定义一个更新进度的handler Handler handler=new Handler(){ public void handleMessage(Message msg){ if(msg.what==0x123){ pd2.setProgress(progressStatus); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void showSpinner(View source){ //环形进度条 ProgressDialog.show(this, "任务执行中","任务执行中,请等待",false,true); } public void showIndeterminate(View source){ pd1=new ProgressDialog(MainActivity.this); pd1.setTitle("任务正在执行中"); pd1.setMessage("任务正在执行中,敬请期待。。。"); pd1.setCancelable(true); pd1.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); pd1.setIndeterminate(true); pd1.show(); } public void showProgress(View source){ progressStatus=0; hasData=0; pd2=new ProgressDialog(MainActivity.this); pd2.setMax(MAX_PROGRESS); pd2.setTitle("任务完成百分比"); pd2.setMessage("耗时任务的完成比"); pd2.setCancelable(false); pd2.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); pd2.setIndeterminate(false); pd2.show(); new Thread(){ public void run(){ while(progressStatus<MAX_PROGRESS){ progressStatus=MAX_PROGRESS* doWork()/data.length; handler.sendEmptyMessage(0x123); } if(progressStatus>=MAX_PROGRESS){ pd2.dismiss(); } } }.start(); } public int doWork() { data[hasData++]=(int) (Math.random()*100); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } return hasData; } }