# Android AlertDialog的幾種用法介紹
## 目錄
1. [AlertDialog概述](#1-alertdialog概述)
2. [基礎AlertDialog使用](#2-基礎alertdialog使用)
3. [帶列表的AlertDialog](#3-帶列表的alertdialog)
4. [單選/多選對話框](#4-單選多選對話框)
5. [自定義布局AlertDialog](#5-自定義布局alertdialog)
6. [Material風格對話框](#6-material風格對話框)
7. [對話框生命周期管理](#7-對話框生命周期管理)
8. [高級技巧與最佳實踐](#8-高級技巧與最佳實踐)
9. [常見問題解決方案](#9-常見問題解決方案)
---
## 1. AlertDialog概述
### 1.1 什么是AlertDialog
AlertDialog是Android提供的一個預置對話框組件,用于:
- 顯示重要信息
- 獲取用戶確認
- 提供選擇項
- 收集簡單輸入
### 1.2 核心特點
- **鏈式調用**:通過Builder模式構建
- **高度可定制**:支持標題、消息、圖標、按鈕和自定義布局
- **生命周期感知**:自動與Activity生命周期綁定
### 1.3 類繼承關系
Dialog └── AlertDialog ├── MaterialAlertDialogBuilder (Material Components) └── AppCompatAlertDialog (Support Library)
---
## 2. 基礎AlertDialog使用
### 2.1 基本構建方法
```kotlin
AlertDialog.Builder(context).apply {
setTitle("溫馨提示")
setMessage("確定要刪除此項嗎?")
setPositiveButton("確定") { dialog, which ->
// 確定操作
}
setNegativeButton("取消", null)
setNeutralButton("稍后提醒") { _, _ ->
// 中性操作
}
}.create().show()
按鈕類型 | 作用場景 | 代碼方法 |
---|---|---|
PositiveButton | 主確認操作(如”確定”) | setPositiveButton() |
NegativeButton | 取消/拒絕操作(如”取消”) | setNegativeButton() |
NeutralButton | 次要操作(如”稍后”) | setNeutralButton() |
// 自定義按鈕文字顏色
val dialog = AlertDialog.Builder(context).create()
dialog.setOnShowListener {
dialog.getButton(AlertDialog.BUTTON_POSITIVE)?.setTextColor(Color.RED)
}
val items = arrayOf("選項1", "選項2", "選項3")
AlertDialog.Builder(context)
.setTitle("請選擇")
.setItems(items) { _, which ->
Toast.makeText(context, "選擇了${items[which]}", Toast.LENGTH_SHORT).show()
}
.show()
ArrayAdapter<String>(this, android.R.layout.select_dialog_item).apply {
add("微信")
add("支付寶")
add("銀行卡")
}.let { adapter ->
AlertDialog.Builder(this)
.setAdapter(adapter) { _, position ->
handlePayment(position)
}
.show()
}
val options = arrayOf("標準模式", "深色模式", "護眼模式")
var currentSelection = 0
AlertDialog.Builder(this)
.setTitle("顯示模式設置")
.setSingleChoiceItems(options, currentSelection) { dialog, which ->
currentSelection = which
}
.setPositiveButton("確認") { _, _ ->
applyDisplayMode(currentSelection)
}
.show()
val selectedItems = booleanArrayOf(true, false, true)
val items = arrayOf("閱讀", "音樂", "運動")
AlertDialog.Builder(this)
.setMultiChoiceItems(items, selectedItems) { _, which, isChecked ->
selectedItems[which] = isChecked
}
.setPositiveButton("確定") { _, _ ->
saveSelections(selectedItems)
}
.show();
val view = layoutInflater.inflate(R.layout.custom_dialog, null)
AlertDialog.Builder(this)
.setView(view)
.setPositiveButton("提交") { _, _ ->
val input = view.findViewById<EditText>(R.id.et_input).text.toString()
handleInput(input)
}
.show()
match_parent
作為對話框寬度WindowManager.LayoutParams
調整對話框尺寸:dialog.window?.setLayout(
(resources.displayMetrics.widthPixels * 0.9).toInt(),
WindowManager.LayoutParams.WRAP_CONTENT
)
implementation 'com.google.android.material:material:1.6.0'
MaterialAlertDialogBuilder(context)
.setTitle("Material對話框")
.setMessage("這是Material Design風格的對話框")
.setBackground(resources.getDrawable(R.drawable.dialog_bg))
.setPositiveButton("確定") { _, _ -> }
.show()
class MyDialogFragment : DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return activity?.let {
AlertDialog.Builder(it)
.setMessage("我會在旋轉后自動恢復")
.create()
} ?: throw IllegalStateException()
}
}
// 錯誤方式(可能導致WindowLeaked)
new AlertDialog.Builder(activity).show();
// 正確方式
MyDialogFragment().show(supportFragmentManager, "tag");
fun showSequentialDialogs() {
val dialog1 = AlertDialog.Builder(this).setMessage("第一步").apply {
setPositiveButton("下一步") { _, _ -> showDialog2() }
}.create()
dialog1.show()
}
private fun showDialog2() {
AlertDialog.Builder(this).setMessage("第二步").show()
}
dialog.window?.attributes?.windowAnimations = R.style.DialogAnimation
原因:未調用create()
直接show()
解決:
val dialog = builder.create()
dialog.show()
dialog.getButton(AlertDialog.BUTTON_POSITIVE)?.isEnabled = false
@Override
protected void onDestroy() {
if(dialog != null && dialog.isShowing()){
dialog.dismiss();
}
super.onDestroy();
}
本文全面介紹了AlertDialog的7種核心用法: 1. 基礎警告對話框 2. 列表選擇對話框 3. 單選/多選對話框 4. 自定義布局對話框 5. Material Design對話框 6. 對話框生命周期管理 7. 高級使用技巧
通過合理使用這些模式,可以構建出既美觀又符合平臺規范的對話框交互體驗。 “`
(注:實際文章需要補充更多示例代碼、示意圖和詳細說明以達到7200字要求,此處為大綱框架)
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。