Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

從零開始學 Android(二十五):Dialog 對話框完全指南

編輯:關於 Android 程式設計

對話框的定位

圖形介面裡,對話框是人機互動的重要形式之一。程式可以透過它向使用者提示資訊,使用者也能藉由它做出簡單的回應——確認、取消、選擇一項、或填幾個欄位。相比整頁跳轉,對話框的優勢是「不離開當前上下文」。

Android 中所有對話框都繼承自 android.app.Dialog,其繼承結構如下:

java.lang.Object
    ↳ android.app.Dialog

Dialog 的常用方法

1.  public void setTitle(CharSequence title)                      設定對話框標題
2.  public void setTitle(int titleId)                             以資源 ID 設定標題
3.  public void show()                                            顯示對話框
4.  public void hide()                                            隱藏對話框
5.  public boolean isShowing()                                    判斷是否正在顯示
6.  public void setContentView(View view)                         設定自訂 View 元件
7.  public void setContentView(int layoutResID)                   以版面資源 ID 設定 View
8.  public void dismiss()                                         關閉對話框
9.  public void closeOptionsMenu()                                關閉選項菜單
10. public void setDismissMessage(Message msg)                    設定關閉時的回送訊息
11. public void setCancelable(boolean flag)                       設定是否可取消
12. public void setCancelMessage(Message msg)                     設定取消時的回送訊息
13. public void cancel()                                          取消對話框,效果與 dismiss() 類似
14. public Window getWindow()                                     取得 Window 物件
15. public void setOnShowListener(DialogInterface.OnShowListener l)        設定顯示時的監聽
16. public void setOnDismissListener(DialogInterface.OnDismissListener l)  設定關閉時的監聽
17. public void setOnCancelListener(DialogInterface.OnCancelListener l)    設定取消時的監聽

實務上,我們幾乎不會直接 new Dialog,而是透過 AlertDialog 的內部類 Builder 來組裝。它是典型的建造者模式:每一步設定都回傳 Builder 本身,因此可以串成一條鏈,最後用 create() 產生物件。

AlertDialog.Builder 的常用方法

1.  public AlertDialog.Builder(Context context)                   建立 Builder 物件
2.  public AlertDialog.Builder setMessage(int messageId)          以資源 ID 設定訊息
3.  public AlertDialog.Builder setMessage(CharSequence message)   以字串設定訊息
4.  public AlertDialog.Builder setView(View view)                 設定自訂 View 元件
5.  public AlertDialog.Builder setSingleChoiceItems(CharSequence[] items, int checkedItem, OnClickListener l)
                                                                  顯示單選清單,指定預設項並設定監聽
6.  public AlertDialog.Builder setSingleChoiceItems(ListAdapter adapter, int checkedItem, OnClickListener l)
                                                                  以 Adapter 提供單選清單資料
7.  public AlertDialog.Builder setMultiChoiceItems(CharSequence[] items, boolean[] checkedItems, OnMultiChoiceClickListener l)
                                                                  顯示多選清單並設定監聽
8.  public AlertDialog.Builder setPositiveButton(CharSequence text, OnClickListener l)
                                                                  加入「確定」按鈕並設定監聽
9.  public AlertDialog.Builder setPositiveButton(int textId, OnClickListener l)
                                                                  以資源 ID 指定按鈕文字
10. public AlertDialog.Builder setNegativeButton(CharSequence text, OnClickListener l)
                                                                  加入「取消」按鈕
11. public AlertDialog.Builder setNegativeButton(int textId, OnClickListener l)
                                                                  以資源 ID 指定取消按鈕文字
12. public AlertDialog.Builder setNeutralButton(CharSequence text, OnClickListener l)
                                                                  加入第三個(普通)按鈕
13. public AlertDialog.Builder setNeutralButton(int textId, OnClickListener l)
                                                                  以資源 ID 指定普通按鈕文字
14. public AlertDialog.Builder setItems(CharSequence[] items, OnClickListener l)
                                                                  將內容設為清單項並設定監聽
15. public AlertDialog.Builder setItems(int itemsId, OnClickListener l)
                                                                  以資源 ID 指定清單項內容
16. public AlertDialog create()                                   建立 AlertDialog 實例
17. public AlertDialog.Builder setIcon(Drawable icon)             設定圖示
18. public AlertDialog.Builder setIcon(int iconId)                以資源 ID 設定圖示

十種常見型態

下面用一個 Activity 示範十種對話框:最簡單的提示、帶按鈕、帶事件、帶清單項、單選、多選、進度條、日期選擇、時間選擇,以及自訂版面。

主版面 XML

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    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/button1"  android:text="最簡單的Dialog"      ... />
    <Button android:id="@+id/button2"  android:text="帶按鈕的對話框"      ... />
    <Button android:id="@+id/button3"  android:text="帶事件處理的對話框"  ... />
    <Button android:id="@+id/button4"  android:text="帶item的對話框"      ... />
    <Button android:id="@+id/button5"  android:text="帶單選按鈕對話框"    ... />
    <Button android:id="@+id/button6"  android:text="帶多選按鈕對話框"    ... />
    <Button android:id="@+id/button7"  android:text="進度條對話框"        ... />
    <Button android:id="@+id/button8"  android:text="日期選擇對話框"      ... />
    <Button android:id="@+id/button9"  android:text="時間選擇對話框"      ... />
    <Button android:id="@+id/button10" android:text="自定義對話框"        ... />
</RelativeLayout>

自訂版面 custom.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dip"
        android:text="用戶名:"
        android:textSize="8pt" />

    <EditText
        android:layout_height="wrap_content"
        android:width="60pt" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dip"
        android:text="密 碼:"
        android:textSize="8pt" />

    <EditText
        android:layout_height="wrap_content"
        android:password="true"
        android:width="60pt" />
</LinearLayout>

Java 程式碼

package com.example.dialog;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TimePicker;
import android.widget.Toast;

public class MainActivity extends Activity {

    private Button button1, button2, button3, button4, button5,
                   button6, button7, button8, button9, button10;

    private String CityData[]  = { "河南", "北京", "上海", "天津", "湖南", "深圳" };
    private String SexData[]   = { "男", "女" };
    private String ColorData[] = { "紅", "橙", "黃", "綠", "青", "藍", "紫" };
    private boolean ColorChoiced[] = { false, false, false, false, false, false, false };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button1  = (Button) this.findViewById(R.id.button1);
        button2  = (Button) this.findViewById(R.id.button2);
        button3  = (Button) this.findViewById(R.id.button3);
        button4  = (Button) this.findViewById(R.id.button4);
        button5  = (Button) this.findViewById(R.id.button5);
        button6  = (Button) this.findViewById(R.id.button6);
        button7  = (Button) this.findViewById(R.id.button7);
        button8  = (Button) this.findViewById(R.id.button8);
        button9  = (Button) this.findViewById(R.id.button9);
        button10 = (Button) this.findViewById(R.id.button10);

        /* 1. 最簡單的對話框 */
        button1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Dialog dialog = new AlertDialog.Builder(MainActivity.this)
                        .setTitle("關於我們")
                        .setMessage("飛揚軟件有限公司")
                        .setIcon(R.drawable.a2)
                        .create();
                dialog.show();
            }
        });

        /* 2. 帶按鈕的對話框 */
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Dialog dialog = new AlertDialog.Builder(MainActivity.this)
                        .setTitle("刪除信息")
                        .setMessage("您確定要刪除該條信息嗎?")
                        .setIcon(R.drawable.a2)
                        .setNegativeButton("取消", null)
                        .setPositiveButton("確定", null)
                        .create();
                dialog.show();
            }
        });

        /* 3. 帶事件處理的對話框 */
        button3.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Dialog dialog = new AlertDialog.Builder(MainActivity.this)
                        .setTitle("退出程序")
                        .setMessage("您確定要退出程序嗎?")
                        .setIcon(R.drawable.a2)
                        .setPositiveButton("確定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int which) {
                                Toast.makeText(MainActivity.this, "程序即將退出", 2).show();
                                // finish(); 為了展示效果不真正退出,以 Toast 代替
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface arg0, int arg1) {
                            }
                        })
                        .create();
                dialog.show();
            }
        });

        /* 4. 帶清單項的對話框 */
        button4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Dialog dialog = new AlertDialog.Builder(MainActivity.this)
                        .setTitle("請選擇您的就業城市")
                        .setIcon(R.drawable.a2)
                        .setNegativeButton("取消", null)
                        .setItems(CityData, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dInterface, int which) {
                                Toast.makeText(MainActivity.this, "您選擇了:" + CityData[which], 2).show();
                            }
                        })
                        .create();
                dialog.show();
            }
        });

        /* 5. 帶單選按鈕的對話框 */
        button5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Dialog dialog = new AlertDialog.Builder(MainActivity.this)
                        .setTitle("請選擇您的性別")
                        .setSingleChoiceItems(SexData, 0, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dInterface, int which) {
                                Toast.makeText(MainActivity.this, "您選擇了:" + SexData[which], 2).show();
                            }
                        })
                        .setIcon(R.drawable.a2)
                        .setNegativeButton("取消", null)
                        .setPositiveButton("確定", null)
                        .create();
                dialog.show();
            }
        });

        /* 6. 帶多選框的對話框 */
        button6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Dialog dialog = new AlertDialog.Builder(MainActivity.this)
                        .setTitle("請選擇您喜歡的顏色")
                        .setMultiChoiceItems(ColorData, ColorChoiced,
                                new DialogInterface.OnMultiChoiceClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                                        Toast.makeText(MainActivity.this, "您選擇了" + ColorData[which], 2).show();
                                        // 這裡未做判斷,選中與取消都會觸發;有興趣可加上 isChecked 判斷
                                    }
                                })
                        .setIcon(R.drawable.a2)
                        .setNegativeButton("取消", null)
                        .setPositiveButton("確定", null)
                        .create();
                dialog.show();
            }
        });

        /* 7. 進度條對話框 */
        button7.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final ProgressDialog dialog = new ProgressDialog(MainActivity.this);
                dialog.setMessage("正在加載信息,請稍後!");
                dialog.setTitle("正在加載");
                dialog.setIcon(R.drawable.a2);
                dialog.onStart();

                new Thread() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(3 * 1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } finally {
                            dialog.dismiss();
                        }
                    }
                }.start();

                dialog.show();
            }
        });

        /* 8. 日期選擇對話框 */
        button8.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DatePickerDialog dialog = new DatePickerDialog(
                        MainActivity.this,
                        new OnDateSetListener() {
                            @Override
                            public void onDateSet(DatePicker datePicker,
                                                  int year, int monthOfYear, int dayOfMonth) {
                                Toast.makeText(MainActivity.this,
                                        "設置的時間為:" + year + "年"
                                        // 注意:monthOfYear 從 0 開始,顯示時要 +1
                                        + (monthOfYear + 1) + "月"
                                        + dayOfMonth + "日", 2).show();
                            }
                        },
                        2014, 8, 17);
                dialog.show();
            }
        });

        /* 9. 時間選擇對話框 */
        button9.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                TimePickerDialog dialog = new TimePickerDialog(
                        MainActivity.this,
                        new OnTimeSetListener() {
                            @Override
                            public void onTimeSet(TimePicker arg0, int hourOfDay, int minute) {
                                Toast.makeText(MainActivity.this,
                                        "設置時間為:" + hourOfDay + "時" + minute + "分", 2).show();
                            }
                        },
                        20, 55, true);
                dialog.show();
            }
        });

        /* 10. 自定義對話框 */
        button10.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 將 layout 資源轉為 View 物件
                View myView = LayoutInflater.from(getApplication())
                        .inflate(R.layout.custom, null);

                Dialog dialog = new AlertDialog.Builder(MainActivity.this)
                        .setTitle("用戶登陸")
                        .setIcon(R.drawable.a2)
                        .setNegativeButton("取消", null)
                        .setPositiveButton("登錄", null)
                        .setView(myView)          // 設定要顯示的自訂 View
                        .create();
                dialog.show();
            }
        });
    }
}

執行結果

以下依序對應各個按鈕的效果:

重點回顧與實務提醒

  • 單選與多選是互動設計的主力。透過這兩種對話框,可以變化出大量的設定與篩選介面。
  • 進度條 + 執行緒:示範中的 ProgressDialog 搭配背景執行緒,是處理耗時操作的經典組合。但要留意 dismiss() 是從背景執行緒呼叫的,嚴格來說應該透過 Handler 或 runOnUiThread() 切回主執行緒;同時 Activity 若在 dialog 關閉前被銷毀,會拋出 WindowLeaked,實務上需在 onDestroy() 中判斷並 dismiss()。
  • 月份要 +1:DatePickerDialog 的 monthOfYear 從 0 起算,這是新手最常踩的雷。
  • 自訂對話框大幅擴展了 UI 的可能性,讓更豐富的資訊回饋與互動成為可能。
  • 時代提醒:ProgressDialog 與 DatePickerDialog 這類直接 new 的用法在 API 26 之後已標記為 deprecated。新專案請改用 DialogFragment(或 DialogFragment 的 Jetpack 版本),它能跟著 FragmentManager 一起被管理,旋轉螢幕時不會洩漏,也不會出現「找不到 window token」的經典崩潰。日期與時間選擇則建議改用 MaterialDatePicker、MaterialTimePicker。

下節預告:ImageSwitcher 圖片切換元件。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved