1.5 顯示進度對話框---ProgressDialog

Android設備的另外一個常見的用戶界面功能是在應用程序執行長時間運行的任務時顯示的Please wait對話框。例如:應用程序可能需要在登錄到服務器以後才能讓用戶使用或者需要在執行計算後才能顯示結果給用戶。在這類情況中,顯示“進度對話框”很有幫助,這樣用戶就知道操作正在進行中。

顯示一個進度(Please wait)對話框:


新建android項目命名爲Dialog。在main.xml中:

<RelativeLayout 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"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/btn_dialog2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Click to display a progress dialog" 
        android:onClick="onClick2"/>

</RelativeLayout>

在DialogActivity.java中:

package com.example.dialoggg;


import android.os.Bundle;
import android.view.View;
import android.app.Activity;
import android.app.ProgressDialog;


public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View v){
//爲了創建一個進度對話框,首先要創建一個ProgressDialog類的實例並調用其show()方法
final ProgressDialog dialog=ProgressDialog.show(this, 
"Doing something", "Please wait...", true);
/**使用Runnable代碼塊創建了一個Thread線程,run()方法中的代碼將在一個單獨的線程中執行,
* 在run()方法中使用sleep()插入延遲5秒*/
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5000);
//5秒之後,調用dismiss()方法關閉進度對話框
dialog.dismiss();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章