萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android AlertDialog.Builder 彈窗構建全攻略:從基礎配置到自定義佈局的最佳實踐

AlertDialog.Builder 是 Android 構建物質設計風格對話框的標準方式。本文通過完整代碼示例,詳解圖標、標題、按鈕 (確定/取消/中立)、點擊回調、顯示/取消邏輯,並延伸介紹自定義佈局、輸入框、列表選擇、進度條等進階用法,助你快速構建優雅交互。

一、 標準雙按鈕對話框:核心代碼

public void showConfirmDialog(Context context) {
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    
    // 1. 基礎屬性
    builder.setIcon(R.drawable.ic_warning);           // 圖標 (可為 ResId 或 Drawable)
    builder.setTitle("確認操作");                     // 標題
    builder.setMessage("您確定要離開嗎?此操作不可撤銷。"); // 正文內容
    
    // 2. 確定按鈕 (正向動作)
    builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // 執行確定邏輯:刪除、提交、跳轉等
            performDestructiveAction();
            dialog.dismiss(); // 可選,默認點擊即消失
        }
    });
    
    // 3. 取消按鈕 (反向/安全動作)
    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // 通常僅關閉,或執行撤銷邏輯
            dialog.dismiss();
        }
    });
    
    // 4. 中立按鈕 (可選,如「稍後提醒」)
    // builder.setNeutralButton("稍後", (dialog, which) -> scheduleReminder());
    
    // 5. 創建並顯示
    AlertDialog dialog = builder.create();
    dialog.show();
    
    // 可選:設置按鈕文字顏色 (需在 show() 後)
    // dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.RED);
}

二、 進階場景速查表

1. 單輸入框對話框 (如修改名稱)

final EditText input = new EditText(context);
input.setHint("請輸入新名稱");
input.setInputType(InputType.TYPE_CLASS_TEXT);

new AlertDialog.Builder(context)
    .setTitle("修改名稱")
    .setView(input) // 直接設置 View
    .setPositiveButton("保存", (dialog, which) -> {
        String newName = input.getText().toString().trim();
        if (!newName.isEmpty()) updateName(newName);
    })
    .setNegativeButton("取消", null)
    .show();

2. 單選列表對話框 (單選項)

final String[] items = {"選項一", "選項二", "選項三"};
int checkedItem = 0; // 默認選中索引

new AlertDialog.Builder(context)
    .setTitle("請選擇")
    .setSingleChoiceItems(items, checkedItem, (dialog, which) -> {
        checkedItem = which; // 記錄選擇
    })
    .setPositiveButton("確定", (dialog, which) -> {
        applySelection(items[checkedItem]);
    })
    .setNegativeButton("取消", null)
    .show();

3. 多選列表對話框 (複選)

final String[] items = {"權限一", "權限二", "權限三"};
final boolean[] checked = {true, false, true}; // 默認狀態

new AlertDialog.Builder(context)
    .setTitle("權限管理")
    .setMultiChoiceItems(items, checked, (dialog, which, isChecked) -> {
        checked[which] = isChecked; // 實時更新狀態
    })
    .setPositiveButton("應用", (dialog, which) -> {
        savePermissions(checked);
    })
    .setNegativeButton("取消", null)
    .show();

4. 進度條對話框 (確定/不確定)

// 不確定進度環 (加載中)
ProgressDialog progress = new ProgressDialog(context);
progress.setMessage("加載中...");
progress.setCancelable(false); // 禁用返回鍵取消
progress.show();

// 確定進度條 (下載/複製)
// 需在異步任務中調用 progress.setProgress(value)
// 現代應用推薦使用 Notification 或自定義 View 替代 ProgressDialog (API 26 棄用)

5. 完全自定義佈局對話框

View customView = LayoutInflater.from(context).inflate(R.layout.dialog_custom, null);
EditText etName = customView.findViewById(R.id.et_name);
CheckBox cbAgree = customView.findViewById(R.id.cb_agree);

new AlertDialog.Builder(context)
    .setTitle("自定義表單")
    .setView(customView)
    .setPositiveButton("提交", (dialog, which) -> {
        String name = etName.getText().toString();
        boolean agree = cbAgree.isChecked();
        submitForm(name, agree);
    })
    .setNegativeButton("取消", null)
    .show();

三、 關鍵最佳實踐

  1. Context 選擇:傳入 Activity 或 ContextThemeWrapper,確保主題正確 (如 Theme.MaterialComponents.DayNight.Dialog.Alert)。避免傳 ApplicationContext (無主題,崩潰風險)。
  2. 內存洩漏防範:匿名內部類持有 Activity 引用。若 Dialog 生命週期超過 Activity (如配置變更),使用靜態內部類 + WeakReference 或 ViewModel/LiveData 解耦。
    簡單場景:Activity 銷毀時 Dialog 自動關閉,通常無大礙。
  3. 取消事件監聽:dialog.setOnCancelListener(d -> onUserCancel()) 處理返回鍵/外部點擊取消邏輯。
  4. 輸入法自動彈出:對包含 EditText 的 Dialog,在 onShow() 中:
    dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
  5. 全屏/底部彈窗:設置 dialog.getWindow().setLayout(MATCH_PARENT, WRAP_CONTENT) + setGravity(Gravity.BOTTOM) 實現 ActionSheet 效果。

四、 現代化替代方案

  • MaterialDialogs (第三方庫):API 更豐富、鏈式調用、Kotlin 友好、支持複雜表單驗證。
  • Jetpack Compose:AlertDialog / Dialog 可組合項,聲明式構建,狀態驅動。
  • BottomSheetDialogFragment:底部彈出面板,符合 Material Design 導航規範。

掌握 AlertDialog.Builder 核心 API 與進階模式,配合合理的架構封裝 (如封裝為 DialogUtils 單例或擴展函數),即可高效構建一致、美觀、健壯的對話框交互體驗。

copyright © 萬盛學電腦網 all rights reserved