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

Android 對話框全面總結:系統 Dialog 與自定義 Dialog 怎麼選

編輯:關於 Android 程式設計

一、什麼是對話框

對話框是一種次要視窗,內含按鈕與各種選項,用來完成某個特定指令或任務。它與一般視窗有別:沒有最大化鈕、沒有最小化鈕,而且大多不能改變大小形狀(「開啟檔案」對話框是少數例外)。

對話框本質上是人機交流的一種管道:使用者對它做設定,程式就執行相應的指令。裡面可以有單選鈕、複選鈕、輸入框等。

二、對話框有什麼用

它不會阻塞主線程,能與使用者做簡短互動,視覺上也給人清爽的感覺。設計得好的對話框不但不惱人,反而會讓使用者覺得「被提醒得很貼心」。

三、怎麼用

1. 系統內建的對話框

  • AlertDialog:最通用的提示/選擇框。
  • ProgressDialog:進度提示(已棄用,改用 ProgressBar 或 Snackbar)。
  • DatePickerDialog:日期選擇。
  • TimePickerDialog:時間選擇。

2. 自定義對話框的兩種寫法

  • 用 LayoutInflater 載入自訂布局,再透過 Builder 的 setView() 塞進去。
  • 繼承 Dialog 類別,在個人建構子中呼叫 setContentView()。

布局檔 activity_main.xml

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:orientation="vertical">

    <Button
        android:id="@+id/show1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="dialog1" />

    <Button
        android:id="@+id/show2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="dialog2" />

    <Button
        android:id="@+id/show3"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="dialog3" />
</LinearLayout>

自定義內容布局 activity_dialog.xml

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="標題"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="這是一個自定義布局的 AlertDialog" />

    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="確定" />
</LinearLayout>

MainActivity:三個按鈕分別示範三種做法。

public class MainActivity extends Activity {
    private Button show1, show2, show3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        show1 = (Button) findViewById(R.id.show1);
        show2 = (Button) findViewById(R.id.show2);
        show3 = (Button) findViewById(R.id.show3);

        View.OnClickListener l = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.show1: showDialog1(); break;
                    case R.id.show2: showDialog2(); break;
                    case R.id.show3: showDialog3(); break;
                }
            }
        };
        show1.setOnClickListener(l);
        show2.setOnClickListener(l);
        show3.setOnClickListener(l);
    }

    /** 寫法一:純系統 AlertDialog */
    private void showDialog1() {
        new AlertDialog.Builder(this)
                .setTitle("dialog 1")
                .setMessage("這是最簡單的 AlertDialog")
                .setPositiveButton("確定", null)
                .setNeutralButton("什麼", null)
                .setNegativeButton("取消", null)
                .create().show();
    }

    /** 寫法二:Builder + setView 塞自訂布局 */
    private void showDialog2() {
        View view = LayoutInflater.from(this).inflate(R.layout.activity_dialog, null);
        final AlertDialog dialog = new AlertDialog.Builder(this).setView(view).create();
        Button ok = (Button) view.findViewById(R.id.button1);
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    /** 寫法三:繼承 Dialog */
    private void showDialog3() {
        new MyDialog(this).show();
    }

    private class MyDialog extends Dialog {
        public MyDialog(Context context) {
            super(context);
            this.setContentView(R.layout.activity_dialog);
            this.setTitle("標題");
            Button b = (Button) findViewById(R.id.button1);
            b.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });
        }
    }
}

四、注意事項

  1. 不要讓對話框氾濫。連續彈三個框打斷操作流程,是最快讓使用者卸载 App 的方式。
  2. 自定義對話框用完記得 dismiss(),Activity 銷毀時也要在 onDestroy 中釋放,否則會視窗洩漏(android.view.WindowLeaked 錯誤就是這樣來的)。
  3. 還有一種做法是把 Activity 的主題設為 Theme.Dialog,讓整個 Activity 長成對話框的樣子。這在需要獨立生命週期或要在 dialog 中承載 Fragment 時很好用。

補充:DialogFragment 才是正解

直接 new Dialog 有個致命問題:它與 Activity 生命週期沒有綁定。旋轉螢幕時 Activity 重建,舊的 Dialog 卻還掛在已銷毀的視窗上,直接 WindowLeaked 崩潰。

正確做法是使用 DialogFragment(或 AndroidX 的 DialogFragment):由 FragmentManager 代管,旋轉時自動重建與恢復,也能用 show() / dismissAllowingStateLoss() 安全控制。

public class MyDialogFragment extends DialogFragment {
    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(requireContext())
                .inflate(R.layout.activity_dialog, null);
        return new AlertDialog.Builder(requireContext())
                .setView(view)
                .setTitle("標題")
                .create();
    }
}

// 呼叫端
new MyDialogFragment().show(getSupportFragmentManager(), "my_dialog");

另外 Material Components 提供的 MaterialAlertDialogBuilder 在系統 Dialog 的基礎上補上了完整的 Material Design 樣式(含 shapeAppearance、背景色、按鈕樣式),新專案建議直接用它取代原生 Builder。

最後想說的是:在這個看顏值的時代,想成為好工程師,得先具備一點設計師的素養——對話框的留白、字級層次、按鈕主次(哪個該是實心、哪個該是文字),都會直接影響使用者對品質的判斷。

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