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);
}
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();
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();
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();
// 不確定進度環 (加載中)
ProgressDialog progress = new ProgressDialog(context);
progress.setMessage("加載中...");
progress.setCancelable(false); // 禁用返回鍵取消
progress.show();
// 確定進度條 (下載/複製)
// 需在異步任務中調用 progress.setProgress(value)
// 現代應用推薦使用 Notification 或自定義 View 替代 ProgressDialog (API 26 棄用)
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();
Activity 或 ContextThemeWrapper,確保主題正確 (如 Theme.MaterialComponents.DayNight.Dialog.Alert)。避免傳 ApplicationContext (無主題,崩潰風險)。dialog.setOnCancelListener(d -> onUserCancel()) 處理返回鍵/外部點擊取消邏輯。onShow() 中:dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);dialog.getWindow().setLayout(MATCH_PARENT, WRAP_CONTENT) + setGravity(Gravity.BOTTOM) 實現 ActionSheet 效果。AlertDialog / Dialog 可組合項,聲明式構建,狀態驅動。掌握 AlertDialog.Builder 核心 API 與進階模式,配合合理的架構封裝 (如封裝為 DialogUtils 單例或擴展函數),即可高效構建一致、美觀、健壯的對話框交互體驗。