1. 程式人生 > >ProgressDialog進度條對話框

ProgressDialog進度條對話框

exce CA pre andro exceptio tom xmlns 對話 sss

(一)

1.效果圖:

技術分享圖片

2.activity_main.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     xmlns:tools="http://schemas.android.com/tools"
 4     android:layout_width="match_parent"
 5     android:layout_height="match_parent"
 6     android:paddingBottom
="@dimen/activity_vertical_margin" 7 android:paddingLeft="@dimen/activity_horizontal_margin" 8 android:paddingRight="@dimen/activity_horizontal_margin" 9 android:paddingTop="@dimen/activity_vertical_margin" 10 tools:context="com.example.administrator.hello3.MainActivity"> 11 12 <
Button 13 android:id="@+id/btn" 14 android:layout_width="match_parent" 15 android:layout_height="wrap_content" 16 android:text="顯示進度條" /> 17 </RelativeLayout>

3.MainActivity.java

 1 package com.example.administrator.hello3;
 2 
 3 import android.app.Activity;
4 import android.app.ProgressDialog; 5 import android.os.Handler; 6 import android.os.Message; 7 import android.support.v7.app.AppCompatActivity; 8 import android.os.Bundle; 9 import android.view.View; 10 import android.widget.Button; 11 12 public class MainActivity extends Activity { 13 14 private Button button; 15 private ProgressDialog pd; 16 private final static int MAXVALUE=100; 17 private int progressStatus =0; //進度條對話框的百分比情況 18 private int data[] = new int[100];//填充數組 19 private int current = 0; 20 private Handler handler = new Handler(){ 21 @Override 22 public void handleMessage(Message msg) { 23 if(msg.what==0x123){ 24 pd.setProgress(progressStatus); 25 } 26 27 super.handleMessage(msg); 28 } 29 }; 30 31 @Override 32 protected void onCreate(Bundle savedInstanceState) { 33 super.onCreate(savedInstanceState); 34 setContentView(R.layout.activity_main); 35 36 button=(Button)findViewById(R.id.btn); 37 button.setOnClickListener(new View.OnClickListener() { 38 @Override 39 public void onClick(View v) { 40 progressStatus=0; 41 current=0; 42 pd=new ProgressDialog(MainActivity.this); 43 pd.setMax(MAXVALUE); 44 pd.setTitle("任務完成百分比"); 45 pd.setMessage("耗時任務完成百分比"); 46 pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 47 48 pd.show(); 49 50 new Thread(new Runnable() { 51 @Override 52 public void run() { 53 while (progressStatus<MAXVALUE){ 54 progressStatus=MAXVALUE*dowork()/data.length; 55 handler.sendEmptyMessage(0x123); 56 } 57 if(progressStatus>=MAXVALUE){ 58 pd.dismiss(); 59 } 60 } 61 }).start(); 62 } 63 }); 64 } 65 66 public int dowork(){ 67 data[current++]=(int)(Math.random()*100); 68 try { 69 Thread.sleep(100); 70 }catch (InterruptedException e){ 71 e.printStackTrace(); 72 } 73 return current; 74 } 75 }

ProgressDialog進度條對話框