**顯示進度對話框**
我們常常有這樣的經歷:執行某一應用程序時,需要等待一會,這時會顯示一個進度(Please Wait)對話框,讓用戶知道操作正在進行。
我們繼續在上一篇中的程序中添加代碼~
1、在上一篇的activity_main.xml文件中添加一個Button,添加后的代碼如下:
~~~
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/btn_dialog"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="Click to display a dialog" />
<Button
android:id="@+id/btn_dialog2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="onClick2"
android:text="Click to display a progress dialog" />
</LinearLayout>
~~~
2、在MainActivity.java中添加一個onClick2()方法,添加的代碼塊如下:
~~~
public void onClick2(View v) {
// ---show the dialog---
final ProgressDialog dialog = ProgressDialog.show(this,
"Doing something", "Please wait...", true);//創建一個進度對話框
new Thread(new Runnable() {//使用Runnable代碼塊創建了一個Thread線程
@Override
public void run() {//run()方法中的代碼將在一個單獨的線程中執行
// TODO Auto-generated method stub
try {
// ---simulate doing something lengthy---
Thread.sleep(5000);//模擬一個耗時5秒的操作
// ---dismiss the dialog---
dialog.dismiss();//5秒鐘后,調用dismiss方法關閉進度對話框
} catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
}
}
}).start();
}
~~~
3、運行,點擊第二個按鈕,效果如下:

5秒后,進度條自動消失,程序恢復原來的狀態~
**[點擊下載完整代碼~](http://download.csdn.net/detail/u012904198/7305765)**
- 前言
- Android應用程序剖析
- (一)——生命周期
- (二)——使用Intent傳數據之通用方式
- (三)——使用靜態變量傳遞數據
- (四)——通過剪切板傳遞數據
- (五)——通過全局變量傳遞數據
- (六)——從Activity返回數據
- adt-bundle-linux-x86_64-20131030下新建工程提示找不到adb和R.java問題的解決
- Eclipse啟動時提示fail to create the Java Virtual Machine問題的解決
- Android常見UI組件之ListView(一)
- Android常見UI組件之ListView(二)——定制ListView
- (七)——顯示對話框窗口
- (八)——顯示進度對話框
- (九)——更復雜的進度對話框
- (十)——使用意圖鏈接活動
- (十一)——從意圖返回結果
- (十二)——使用意圖傳遞數據的幾種方式
- (十三)——碎片(一)
- (十四)——在運行時添加碎片(附源碼)
- (十五)——碎片的生命周期(附源碼)
- (十六)——碎片之間進行交互(附源碼)
- (十七)——使用意圖調用內置應用程序
- (十八)——使用意圖篩選器和實現瀏覽網頁(附源碼)