一個對話框一般是一個出現在當前Activity之上的一個小窗口. 處於下面的Activity失去焦點, 對話框接受所有的用戶交互. 對話框一般用於提示信息和與當前應用程序直接相關的小功能.
Android API 支持下列類型的對話框對象:
警告對話框 AlertDialog: 一個可以有0到3個按鈕, 一個單選框或復選框的列表的對話框. 警告對話框可以創建大多數的交互界面, 是推薦的類型.
進度對話框 ProgressDialog: 顯示一個進度環或者一個進度條. 由於它是AlertDialog的擴展, 所以它也支持按鈕.
日期選擇對話框 DatePickerDialog: 讓用戶選擇一個日期.
時間選擇對話框 TimePickerDialog: 讓用戶選擇一個時間.
如果你希望自定義你的對話框, 可以擴展Dialog類.
Showing a Dialog 顯示對話框
一個對話框總是被創建和顯示為一個Activity的一部分. 你應該在Activity的onCreateDialog(int)中創建對話框. 當你使用這個回調函數時,Android系統自動管理每個對話框的狀態並將它們和Activity連接, 將Activity變為對話框的"所有者". 這樣,每個對話框從Activity繼承一些屬性. 例如,當一個對話框打開時, MENU鍵會顯示Activity的菜單, 音量鍵會調整Activity當前使用的音頻流的音量.
注意: 如果你希望在onCreateDialog()方法之外創建對話框, 它將不會依附在Activity上. 你可以使用setOwnerActivity(Activity)來將它依附在Activity上.
當你希望顯示一個對話框時, 調用showDialog(int)並將對話框的id傳給它.
當一個對話框第一次被請求時,Android調用onCreateDialog(int). 這里是你初始化對話框的地方. 這個回調函數傳入的id和showDialog(int)相同. 創建對話框之后,將返回被創建的對象.
在對話框被顯示之前,Android還會調用onPrepareDialog(int, Dialog). 如果你希望每次顯示對話框時有動態更改的內容, 那么就改寫這個函數. 該函數在每次一個對話框打開時都調用. 如果你不定義該函數,則對話框每次打開都是一樣的. 該函數也會傳入對話框的id以及你在onCreateDialog()中創建的Dialog對象.
最好的定義onCreateDialog(int) 和onPrepareDialog(int, Dialog) 的方法就是使用一個switch語句來檢查傳入的id. 每個case創建相應的對話框. 例如, 一個游戲使用兩個對話框: 一個來指示游戲暫停,另一個指示游戲結束. 首先, 為它們定義ID:static final int DIALOG_PAUSED_ID = 0;
static final int DIALOG_GAMEOVER_ID = 1;
然后, 在onCreateDialog(int)中加入一個switch語句:
- protected Dialog onCreateDialog(int id) {
- Dialog dialog;
- switch(id) {
- case DIALOG_PAUSED_ID:
- // do the work to define the pause Dialog
- break;
- case DIALOG_GAMEOVER_ID:
- // do the work to define the game over Dialog
- break;
- default:
- dialog = null;
- }
- return dialog;
- }
在需要顯示對話框是, 調用showDialog(int), 傳入對話框的id:
showDialog(DIALOG_PAUSED_ID);Dismissing a Dialog 解除對話框
當你准備關閉對話框時, 你可以使用dismiss()函數. 如果需要的話, 你也可以從Activity調用dismissDialog(int), 二者效果是一樣的.
如果你使用onCreateDialog(int)來管理你的對話框的狀態, 那么每次你的對話框被解除時, 該對話框對象的狀態會被Activity保存. 如果你決定你不再需要這個對象或者需要清除對話框的狀態, 那么你應該調用 removeDialog(int). 這將把所有該對象的內部引用移除, 如果該對話框在顯示的話將被解除.
Using dismiss listeners 使用解除監聽器
如果你希望在對話框解除時運行某些程序, 那么你應該給對話框附加一個解除監聽器.
首先定義DialogInterface.OnDismissListener接口. 這個接口只有一個方法, onDismiss(DialogInterface), 該方法將在對話框解除時被調用.
然后將你的OnDismissListener實現傳給setOnDismissListener().
然而,注意對話框也可以被"取消". 這是一個特殊的情形, 它意味着對話框被用戶顯式的取消掉. 這將在用戶按下"back"鍵時, 或者對話框顯式的調用cancel()(按下對話框的cancel按鈕)時發生. 當一個對話框被取消時, OnDismissListener將仍然被通知, 但如果你希望在對話框被顯示取消(而不是正常解除)時被通知, 則你應該使用setOnCancelListener()注冊一個DialogInterface.OnCancelListener.
Creating an AlertDialog 創建警告對話框
An AlertDialog is an extension of the Dialog class. It is capable of constructing most dialog user interfaces and is the suggested dialog type. You should use it for dialogs that use any of the following features:
一個警告對話框是對話框的一個擴展. 它能夠創建大多數對話框用戶界面並且是推薦的對話框類新星. 對於需要下列任何特性的對話框,你都應該使用它:
一個標題
一條文字消息
1個-3個按鈕
一個可選擇的列表(單選框或者復選框)
要創建一個AlertDialog, 使用AlertDialog.Builder子類. 使用AlertDialog.Builder(Context)來得到一個Builder, 然后使用該類的公有方法來定義AlertDialog的屬性. 設定好以后, 使用create()方法來獲得AlertDialog對象.
下面的主題展示了如何為AlertDialog定義不同的屬性, 使用AlertDialog.Builder類. 如果你使用這些示例代碼, 你可以在onCreateDialog()中返回最后的Dialog對象來獲得圖片中對話框的效果.
Adding buttons 增加按鈕

- AlertDialog.Builder builder = new AlertDialog.Builder(this);
- builder.setMessage("Are you sure you want to exit?")
- .setCancelable(false)
- .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int id) {
- MyActivity.this.finish();
- }
- })
- .setNegativeButton("No", new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int id) {
- dialog.cancel();
- }
- });
- AlertDialog alert = builder.create();
注意:對每種按鈕類型,只能為AlertDialog創建一個。也就是說,一個AlertDialog不能有兩個以上的"positive"按鈕。這使得可能的按鈕數量最多為三個:肯定、否定、中性。這些名字和實際功能沒有聯系,但是將幫助你記憶它們各做什么事情。

- final CharSequence[] items = {"Red", "Green", "Blue"};
- AlertDialog.Builder builder = new AlertDialog.Builder(this);
- builder.setTitle("Pick a color");
- builder.setItems(items, new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int item) {
- Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
- }
- });
- AlertDialog alert = builder.create();
Adding checkboxes and radio buttons 增加單選框和復選框

注意: 要在你的acitivity離開和暫停時保存選擇, 你必須在activity的聲明周期中正確的保存和恢復設置。為了永久性保存選擇,你必須使用數據存儲技術中的一種。
要創建一個具有單選列表的AlertDialog,只需將一個例子中的setItems()換成 setSingleChoiceItems():
- final CharSequence[] items = {"Red", "Green", "Blue"};
- AlertDialog.Builder builder = new AlertDialog.Builder(this);
- builder.setTitle("Pick a color");
- builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int item) {
- Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
- }
- });
- AlertDialog alert = builder.create();
Creating a ProgressDialog 創建進度對話框

打開一個進度對話框很簡單,只需要調用 ProgressDialog.show()即可。例如,上圖的對話框可以不通過onCreateDialog(int),而直接顯示:
ProgressDialog dialog = ProgressDialog.show(MyActivity.this, "",
"Loading. Please wait...", true);
第一個參數是應用程序上下文。第二個為對話框的標題(這里為空),第三個為對話框內容, 最后一個為該進度是否為不可確定的(這只跟進度條的創建有關,見下一節)。
進度對話框的默認樣式為一個旋轉的環。如果你希望顯示進度值,請看下一節。
Showing a progress bar 顯示進度條
使用一個動畫進度條來顯示進度:
使用 ProgressDialog(Context)構造函數來初始化一個ProgressDialog對象。
將進度樣式設置為"STYLE_HORIZONTAL",使用setProgressStyle(int)方法。並且設置其它屬性,例如內容等。
在需要顯示時調用show()或者從onCreateDialog(int)回調函數中返回該ProgressDialog。
你可以使用 setProgress(int)或者incrementProgressBy(int)來增加顯示的進度。
例如,你的設置可能像這樣:ProgressDialog progressDialog;
progressDialog = new ProgressDialog(mContext);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
設置很簡單。大部分創建進度對話框需要的代碼是在更新它的進程中。你可能需要在一個新的線程中更新它,並使用Handler來將進度報告給Activity。如果你不熟悉使用Handler和另外的線程,請看下列例子,該例子使用了一個新的線程來更新進度。
Example ProgressDialog with a second thread 例--使用一個線程來顯示進度對話框
這個例子使用一個線程來跟蹤一個進程的進度(其實為從1數到100)。每當進度更新時,該線程通過Handler給主activity發送一個消息。主Activity更新ProgressDialog.package com.example.progressdialog;
- import android.app.Activity;
- import android.app.Dialog;
- import android.app.ProgressDialog;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.Message;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- public class NotificationTest extends Activity {
- static final int PROGRESS_DIALOG = 0;
- Button button;
- ProgressThread progressThread;
- ProgressDialog progressDialog;
- /** Called when the activity is first created. */
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- // Setup the button that starts the progress dialog
- button = (Button) findViewById(R.id.progressDialog);
- button.setOnClickListener(new OnClickListener(){
- public void onClick(View v) {
- showDialog(PROGRESS_DIALOG);
- }
- });
- }
- protected Dialog onCreateDialog(int id) {
- switch(id) {
- case PROGRESS_DIALOG:
- progressDialog = new ProgressDialog(NotificationTest.this);
- progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
- progressDialog.setMessage("Loading...");
- progressThread = new ProgressThread(handler);
- progressThread.start();
- return progressDialog;
- default:
- return null;
- }
- }
- // Define the Handler that receives messages from the thread and update the progress
- final Handler handler = new Handler() {
- public void handleMessage(Message msg) {
- int total = msg.getData().getInt("total");
- progressDialog.setProgress(total);
- if (total >= 100){
- dismissDialog(PROGRESS_DIALOG);
- progressThread.setState(ProgressThread.STATE_DONE);
- }
- }
- };
- /** Nested class that performs progress calculations (counting) */
- private class ProgressThread extends Thread {
- Handler mHandler;
- final static int STATE_DONE = 0;
- final static int STATE_RUNNING = 1;
- int mState;
- int total;
- ProgressThread(Handler h) {
- mHandler = h;
- }
- public void run() {
- mState = STATE_RUNNING;
- total = 0;
- while (mState == STATE_RUNNING) {
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- Log.e("ERROR", "Thread Interrupted");
- }
- Message msg = mHandler.obtainMessage();
- Bundle b = new Bundle();
- b.putInt("total", total);
- msg.setData(b);
- mHandler.sendMessage(msg);
- total++;
- }
- }
- /* sets the current state for the thread,
- * used to stop the thread */
- public void setState(int state) {
- mState = state;
- }
- }
- }

例如,創建如圖所示的對話框:
創建一個xml布局custom_dialog.xml:
- http://schemas.android.com/apk/res/android"
- android:id="@+id/layout_root"
- android:orientation="horizontal"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:padding="10dp"
- >
- android:layout_width="wrap_content"
- android:layout_height="fill_parent"
- android:layout_marginRight="10dp"
- />
- android:layout_width="wrap_content"
- android:layout_height="fill_parent"
- android:textColor="#FFF"
- />
將以上布局設為對話框的content view,並且定義ImageView 和 TextView的內容:
- Context mContext = getApplicationContext();
- Dialog dialog = new Dialog(mContext);
- dialog.setContentView(R.layout.custom_dialog);
- dialog.setTitle("Custom Dialog");
- TextView text = (TextView) dialog.findViewById(R.id.text);
- text.setText("Hello, this is a custom dialog!");
- ImageView image = (ImageView) dialog.findViewById(R.id.image);
- image.setImageResource(R.drawable.android);
使用前面所講的方法顯示對話框。
一個使用Dialog類建立的對話框必須有一個標題。如果你不調用setTitle(),那么標題區域會保留空白。如果你不希望有一個標題,那么你應該使用AlertDialog類來創建自定義對話框。然而,由於一個AlertDialog使用AlertDialog.Builder類來建立最方便,所以你沒有方法使用setContentView(int),而是只能使用setView(View)。該方法接受一個View對象,所以你需要從xml中展開你的根View。
要展開一個xml布局,使用 getLayoutInflater() (或 getSystemService())取得LayoutInflater,然后調用inflate(int, ViewGroup),第一個參數為布局id,而第二個參數為根view的id。現在,你可以使用展開后的布局來找到View對象並定義ImageView和TextView元素的內容。然后實例化AlertDialog.Builder並使用setView(View)來為對話框設置展開后的布局。例如:
- AlertDialog.Builder builder;
- AlertDialog alertDialog;
- Context mContext = getApplicationContext();
- LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
- View layout = inflater.inflate(R.layout.custom_dialog,
- (ViewGroup) findViewById(R.id.layout_root));
- TextView text = (TextView) layout.findViewById(R.id.text);
- text.setText("Hello, this is a custom dialog!");
- ImageView image = (ImageView) layout.findViewById(R.id.image);
- image.setImageResource(R.drawable.android);
- builder = new AlertDialog.Builder(mContext);
- builder.setView(layout);
- alertDialog = builder.create();
顯示對話框
對話框經常作為Activity的一部分來創建和顯示。你通常應該從protected Dialog Activity.onCreateDialog (int id) 回調方法里創建對話框。當你使用這個回調函數時,Android系統會有效的設置這個Activity為每個對話框的所有者,從而自動管理每個對話框的狀態並掛靠到Activity上。這樣,每個對話框繼承這個Activity的特定屬性。比如,當一個對話框打開時,菜單鍵顯示為這個Activity定義的選項菜單,音量鍵修改Activity使用的音頻流。
- 注意: 如果你決定在onCreateDialog()方法之外創建一個對話框,它將不會被附着到活動上。不過,你可以通過setOwnerActivity(Activity)把它附着到一個活動上。
當你想要顯示一個對話框時,調用showDialog(int id) 方法並傳遞一個唯一標識這個對話框的整數。
當對話框第一次被請求時,Android從你的Activity中調用onCreateDialog(int id),你應該在這里初始化這個對話框Dialog。這個回調方法被傳以和showDialog(int id)相同的ID。當你創建這個對話框后,在Activity的最后返回這個對象。
在對話框被顯示之前,Android還調用了可選的回調函數onPrepareDialog(int id, Dialog). 如果你想在每一次對話框被打開時改變它的任何屬性,你可以定義這個方法。這個方法在每次打開對話框時被調用,而onCreateDialog(int) 僅在對話框第一次打開時被調用。如果你不定義onPrepareDialog(),那么這個對話框將保持和上次打開時一樣。這個方法也被傳遞以對話框的ID,和在onCreateDialog()中創建的對話框對象。(個人理解是,在本Activity里第一次show某個Dialog,則先調用onCreateDialog,得到返回的Dialog對象並掛靠在Activity,保存Dialog對象的引用,然后才顯示Dialog。這樣子,下次再show Dialog就不用重新創建Dialog對象,而是重用舊的)
定義onCreateDialog(int) 和 onPrepareDialog(int, Dialog) 回調函數的最佳方法是使用一個switch 語句來檢查傳遞進來的id 參數。每個case 應該檢查一個唯一的對話框ID然后創建和定義相應的對話框。比如,想象一下一個游戲使用兩個不同的對話框:一個用來指示這個游戲已經暫停而另一個來指示游戲結束。首先,為每個對話框定義一個常量:
- static final int DIALOG_PAUSED_ID = 0;
- static final int DIALOG_GAMEOVER_ID = 1;
然后,為每一個ID用一個switch case定義這個onCreateDialog(int) 回調函數:
- protected Dialog onCreateDialog(int id) {
- Dialog dialog;
- switch(id) {
- case DIALOG_PAUSED_ID:
- // do the work to define the pause Dialog
- break;
- case DIALOG_GAMEOVER_ID:
- // do the work to define the game over Dialog
- break;
- default:
- dialog = null;
- }
- return dialog;
- }
當是時候顯示其中之一的對話框時,使用對話框ID調用showDialog(int):
- showDialog(DIALOG_PAUSED_ID);
消除對話框Dismissing a Dialog
當你准備關閉對話框時,你可以通過對這個對話框調用dismiss()來消除它。如果需要,你還可以從這個Activity中調用dismissDialog(int id) 方法,這實際上將為你對這個對話框調用dismiss() 方法。
如果你想使用onCreateDialog(int id) 方法來管理你對話框的狀態(就如同在前面的章節討論的那樣),然后每次你的對話框消除的時候,這個對話框對象的狀態將由該Activity保留。如果你決定不再需要這個對象或者清除該狀態是重要的,那么你應該調用removeDialog(int id)。這將刪除任何內部對象引用而且如果這個對話框正在顯示,它將被消除。
使用消除偵聽器Using dismiss listeners
如果你希望你的應用程序在一個對話框消亡的時候執行一些流程,那么你應該附着一個on-dismiss偵聽器到對話框上。
- @Override
- protected void onPrepareDialog(int id, Dialog dialog) {
- switch(id){
- case PROGRESS_DIALOG:
- dialog.setOnDismissListener(new DialogInterface.OnDismissListener(){
- @Override
- public void onDismiss(DialogInterface dialog) {
- Toast.makeText(getApplicationContext(),
- "dismiss listener!",
- Toast.LENGTH_SHORT)
- .show();
- }
- });
- }
- }
然而, 請注意對話框也可以被“取消”。這是一個表明對話框被用戶顯示取消的特殊情況。這將在用戶按“返回”按鈕時發生,或者這個對話框顯示的調用cancel() (也許通過對話框上的一個“取消”按鈕)。當一個對話框被取消時,這個OnDismissListener 依然會被通知到,但是如果你希望在對話框被顯示取消時被通知到(而不是通常的消除方式),那么你應該通過setOnCancelListener()注冊一個DialogInterface.OnCancelListener 。
目前個人學習發現,一般情況下,調用dialog.cancel()就會觸發onCancelLister。而點擊AlertDialog的NegativeButton (Cancel/No)是不會觸發的。對於setOnCancelListener()要注意的是,這里有兩個setOnCancelListener(),但返回值不同:
- //AlertDialog.Builder調用的
- public AlertDialog.Builder setOnCancelListener (DialogInterface.OnCancelListener onCancelListener)
- //Dialog調用的
- public void setOnCancelListener (DialogInterface.OnCancelListener listener)
警告對話框AlertDialog的使用
為了創建一個警告對話框,使用AlertDialog.Builder 子類。通過AlertDialog.Builder(Context)獲取一個構造器然后使用這個類的公共方法來定義警告對話框的所有屬性。當得到構造器后,通過create().方法來獲取警告對話框對象。有時我是不調用create()的,而是在設置好了后直接調用show()顯示AlertDialog。
增加按鈕Adding buttons
這就是我一開始很想知道的究竟如何添加Yes/No,Ok/Cancel這樣的按鈕。原來是通過setPositiveButton(...)響應Yes/Ok的點擊,setNeutralButton(...)響應中立行為的點擊,setNegativeButton(...)響應No/Cancel的點擊。注意,只能各自設置一個按鈕來響應點擊事件。
- AlertDialog.Builder builder = new AlertDialog.Builder(this);
- builder.setMessage("Are you sure you want to exit?")
- .setCancelable(false)
- .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int id) {
- MyActivity.this.finish();
- }
- })
- .setNegativeButton("No", new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int id) {
- dialog.cancel();
- }
- });
- AlertDialog alert = builder.create();
首先,為這個對話框添加一個消息setMessage(CharSequence)。然后,開始函數鏈並設置該對話框為不能取消not cancelable (因此用戶不能使用返回按鈕關閉這個對話框)。對每個按鈕,使用任一set...Button() 方法,比如setPositiveButton(),該方法接受按鈕名稱以及一個定義用戶選中按鈕后所采取動作的DialogInterface.OnClickListener。
增加一個列表Adding a list
- final CharSequence[] items = {"Red", "Green", "Blue"};
- AlertDialog.Builder builder = new AlertDialog.Builder(this);
- builder.setTitle("Pick a color");
- builder.setItems(items, new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int item) {
- Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
- }
- });
- AlertDialog alert = builder.create();
首先,用setTitle(CharSequence)方法給對話框添加一個標題。然后,添加用setItems()添加一個可選項列表,該列表接受一組顯示的items和一個DialogInterface.OnClickListener 來定義用戶選中按鈕后所采取動作。
增加復選框和單選按鈕
要在對話框里創建一個多選項列表(checkboxes)或者單選項(radio buttons),可分別調用setMultiChoiceItems() 和setSingleChoiceItems() 方法。如果你在onCreateDialog()回調函數中創建這些可選列表,Android會幫你管理列表狀態。只要這個活動是激活的,對話框會記住之前選中的items,但如果用戶退出這個活動,用戶選擇將丟失。
注意: 為了在用戶離開或暫停這個活動的時候能夠保存選擇,你必須通過活動生命期Activity Lifecycle來恰當的保存和恢復設置。為了永久保存選項,即使活動進程被完全終止,你需要使用數據存儲Data Storage技術。
- final CharSequence[] items = {"Red", "Green", "Blue"};
- AlertDialog.Builder builder = new AlertDialog.Builder(this);
- builder.setTitle("Pick a color");
- builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int item) {
- Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
- }
- });
- AlertDialog alert = builder.create();
setSingleChoiceItems() 的第二個參數是一個checkedItem整型數值,指示了基於0的缺省選擇項的位置。“-1”代表不會有默認選擇項。
進度對話框Progress Dialog的使用
ProgressDialog是AlertDialog類的一個擴展,可以為一個未定義進度的任務顯示一個旋轉輪形狀的進度動畫,或者為一個指定進度的任務顯示一個進度條。
可以簡單地通過調用ProgressDialog.show()方法來顯示一個進度對話框,而通過onCreateDialog(int)回調管理這個對話框是可選的,如下所示:
- ProgressDialog.show(this, // context
- "", // title
- "Loading. Please wait...", // message
- true); //進度是否是不確定的,這只和創建進度條有關
進度對話框的缺省類型是一個旋轉輪,運行看到的是以下效果: