Android Compose UI Dialogs 與 Bottom Sheets

當我們需要請求使用者確認,或顯示補充資訊時,會使用 Dialog (對話框) 或 Bottom Sheet (底部彈出視窗)。

AlertDialog (警告對話框)

最標準的對話框。

if (showDialog) {
    AlertDialog(
        onDismissRequest = { showDialog = false }, // 點擊外部區域關閉
        title = { Text("確認刪除?") },
        text = { Text("刪除後將無法復原資料。") },
        confirmButton = {
            TextButton(onClick = { 
                deleteItem()
                showDialog = false 
            }) {
                Text("刪除")
            }
        },
        dismissButton = {
            TextButton(onClick = { showDialog = false }) {
                Text("取消")
            }
        },
        icon = { Icon(Icons.Default.Warning, contentDescription = null) }
    )
}

注意:Dialog 是透過 if 判斷來決定是否顯示在 Composition 中。

ModalBottomSheet (底部彈出視窗)

Material 3 的 Bottom Sheet 用法。

val sheetState = rememberModalBottomSheetState()
var showBottomSheet by remember { mutableStateOf(false) }

if (showBottomSheet) {
    ModalBottomSheet(
        onDismissRequest = { showBottomSheet = false },
        sheetState = sheetState
    ) {
        // Sheet 內容
        Column(modifier = Modifier.padding(16.dp)) {
            Text("選擇操作", style = MaterialTheme.typography.titleLarge)
            Spacer(Modifier.height(16.dp))
            Button(onClick = { /* ... */ }) { Text("分享") }
            Button(onClick = { /* ... */ }) { Text("複製連結") }
        }
    }
}

Custom Dialog (自定義對話框)

如果你需要完全自定義外觀的 Dialog(例如全螢幕廣告、Loading 轉圈圈),可以使用基礎的 Dialog Composable。

Dialog(onDismissRequest = { /* ... */ }) {
    // 這裡可以放任何 Composable
    Card(shape = RoundedCornerShape(16.dp)) {
        Box(
            modifier = Modifier.size(200.dp),
            contentAlignment = Alignment.Center
        ) {
            CircularProgressIndicator()
        }
    }
}

小結

  • AlertDialog:用於阻斷式的操作確認。
  • ModalBottomSheet:用於提供更多操作選項或次級內容,且單手操作友善。
  • 記得管理好 show/hide 的狀態變數。