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

Android 各種對話框總結筆記:從 AlertDialog 到自定義樣式

編輯:關於 Android 程式設計

對話框是 Android 中最常被使用、也最容易被寫得雜亂的元件。以下把常見的幾種類型整理成一份可直接複製的筆記。

一、確定/取消對話框(帶圖示)

// 參數:上下文、主題
new AlertDialog.Builder(this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT)
        .setTitle("標題")
        .setMessage("內容")
        .setIcon(R.drawable.ic_launcher)
        // 回應點擊事件
        .setPositiveButton("確定", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this, "確定", 0).show();
            }
        })
        .setNegativeButton("取消", null)
        .show();    // 別忘了 show()

這裡有個實務上的建議:箭頭內的 new OnClickListener() 實際上是 DialogInterface.OnClickListener,為了避免 import 混淆,建議寫成完整名稱或明確 import。另外,取消按鈕的監聽器傳 null 是合法且常見的寫法,因為系統會自動關閉對話框。

二、單選對話框

final String[] strs = new String[]{ "男", "女", "不告訴你" };

new AlertDialog.Builder(this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT)
        .setTitle("標題")
        .setIcon(R.drawable.ic_launcher)
        // 參數:String 陣列、預設選項索引、回應事件
        .setSingleChoiceItems(strs, 2, new DialogInterface.OnClickListener() {
            // which 為所選項的陣列索引
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this, strs[which], 0).show();
            }
        })
        .show();

注意單選對話框點擊項目不會自動關閉,這是刻意設計,讓使用者可以在選項間來回比較。如果需要點完就關閉,要在 onClick 中自行呼叫 dialog.dismiss()。

三、多選對話框

final String[] strs = new String[]{ "香蕉", "蘋果", "梨子" };

AlertDialog.Builder dialog = new AlertDialog.Builder(
        this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT)
        .setTitle("標題")
        .setIcon(R.drawable.ic_launcher)
        // 參數:選項陣列、初始勾選狀態陣列、回應事件
        .setMultiChoiceItems(strs, new boolean[]{ true, true, false },
                new DialogInterface.OnMultiChoiceClickListener() {
                    // which:所選項索引;isChecked:該項目前的勾選狀態
                    @Override
                    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                        Log.d("test", "which = " + which + " : isChecked = " + isChecked);
                    }
                });
dialog.create().show();

這裡要注意初始勾選狀態陣列的長度必須與選項陣列一致,否則會有undefined 行為。實務上如果要保留使用者最後的勾選結果,通常會在 Activity 中用一個 boolean[] 成員變數記錄,並在每次回呼中更新它,而不是依賴對話框自身的狀態。

四、進度對話框(不確定模式)

ProgressDialog pd = new ProgressDialog(this);
pd.setTitle("標題");
pd.setMessage("請稍候……");
pd.show();

這個寫法要特別小心:ProgressDialog 從 Android 5.0(API 26 標記)開始已被官方標記為 deprecated。它會以帶遮罩的模態視窗阻擋所有互動,在現代 Android 的設計指引中屬於反模式。如果只是短暫的等待,請改用 ProgressBar 放在畫面內;如果是長時間操作,應該顯示明確的進度並允許使用者離開。

五、進度條對話框

final ProgressDialog pd = new ProgressDialog(this);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);   // 只有兩種樣式
pd.setMax(100);
pd.setTitle("標題");
pd.setMessage("請稍候……");
pd.show();

new Thread() {
    public void run() {
        for (int i = 1; i < 100; i++) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            pd.setProgress(i);
        }
        // 任何執行緒都可以關閉
        pd.dismiss();
    }
}.start();

這裡有兩個問題值得指出。第一,從子執行緒呼叫 setProgress() 之所以能運作,是因為 ProgressDialog 內部做了執行緒封送,但這種隱含行為不該被依賴。第二,如果在進度還沒跑完時使用者旋轉螢幕,Activity 重建而 pd 指向已銷毀的視窗,dismiss() 就會拋出 IllegalArgumentException。正確做法是把進度狀態放在 ViewModel 中,讓 UI 依狀態自行渲染。

六、自定義內容對話框

最簡單的方式是直接塞一個 EditText:

final EditText et_text = new EditText(this);

new AlertDialog.Builder(this)
        .setTitle("請輸入")
        .setIcon(android.R.drawable.ic_dialog_info)
        .setView(et_text)                       // 放入自訂檢視
        .setPositiveButton("確定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this,
                        et_text.getText().toString(), 0).show();
            }
        })
        .setNegativeButton("取消", null)
        .show();

如果是比較複雜的表單,則改用布局檔:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/llToast"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="16dp">

    <EditText
        android:id="@+id/et_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="請輸入名稱" />

</LinearLayout>

View view = LayoutInflater.from(this)
        .inflate(R.layout.dialog_custom, null);
final EditText et = view.findViewById(R.id.et_name);

new AlertDialog.Builder(this)
        .setTitle("請輸入")
        .setView(view)
        .setPositiveButton("確定", (dialog, which) ->
                Toast.makeText(this, et.getText().toString(), 0).show())
        .setNegativeButton("取消", null)
        .show();

七、選擇這一切的替代方案

如果你正在寫新專案,可以考慮改用 Material Components 的 MaterialAlertDialogBuilder。它與上面的用法幾乎一致,但自動套用 Material Design 的樣式、支援深色模式、按鈕位置符合無障礙規範,並提供 setView() 以外更完整的自訂能力:

new MaterialAlertDialogBuilder(this)
        .setTitle("標題")
        .setMessage("內容")
        .setPositiveButton("確定", null)
        .setNegativeButton("取消", null)
        .show();

另外,對話框的生命週期管理是新手最容易忽略的一環。直接 new 出來的 Dialog 不會隨 Fragment/Activity 狀態自動還原,建議改用 DialogFragment(或 DialogFragment 的 Compose 版本),把顯示邏輯交給 FragmentManager 管理,這樣旋轉螢幕、背景回收時都能正確還原,也能避免最常見的 WindowManager.BadTokenException。

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