直接來上菜,來跟對話框聊聊天吧~(笑)。
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun MyApp() {
val title = remember { mutableStateOf("") }
val message = remember { mutableStateOf("") }
val keyboardController = LocalSoftwareKeyboardController.current
val focusManager = LocalFocusManager.current
val showAlertDialog = remember { mutableStateOf(false) }
val scope = rememberCoroutineScope()
val snackbarHostState = remember { SnackbarHostState() }
Scaffold(
snackbarHost = {SnackbarHost(hostState = snackbarHostState)}
) { paddingValues ->
Column(modifier = Modifier
.fillMaxSize()
.padding(paddingValues),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.Start
) {
Row(modifier = Modifier
.fillMaxWidth()
.padding(8.dp),
verticalAlignment = Alignment.CenterVertically
) {
Text(text = "標題:",
modifier = Modifier
.weight(1f)
.padding(8.dp),
textAlign = TextAlign.Center,
fontSize = 24.sp
)
TextField(value = title.value,
onValueChange = {title.value = it},
modifier = Modifier
.weight(2f)
.padding(8.dp),
maxLines = 1,
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
keyboardActions = KeyboardActions(
onDone = {
keyboardController?.hide()
focusManager.clearFocus()
}
)
)
}
Row(modifier = Modifier
.fillMaxWidth()
.padding(8.dp),
verticalAlignment = Alignment.CenterVertically
) {
Text(text = "內文:",
modifier = Modifier
.weight(1f)
.padding(8.dp),
textAlign = TextAlign.Center,
fontSize = 24.sp
)
TextField(value = message.value,
onValueChange = {message.value = it},
modifier = Modifier
.weight(2f)
.padding(8.dp),
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
keyboardActions = KeyboardActions(
onDone = {
keyboardController?.hide()
focusManager.clearFocus()
}
)
)
}
Row(modifier = Modifier
.fillMaxWidth()
.padding(8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center
) {
OutlinedButton(onClick = {
if(title.value.isNotEmpty()&&message.value.isNotEmpty()){
keyboardController?.hide()
focusManager.clearFocus()
showAlertDialog.value = true
}
}) {
Text(text = "來個對話框吧")
}
}
if(showAlertDialog.value){
AlertDialog(
icon = { Icon(imageVector = Icons.Default.Info, contentDescription = null)},
title = {Text(title.value)},
text = {Text(message.value)},
onDismissRequest = {
showAlertDialog.value=false
scope.launch {
snackbarHostState.showSnackbar(message = "不喜歡,下次別亂按了。")
}
},
confirmButton = {
TextButton(onClick = {
showAlertDialog.value = false
scope.launch {
snackbarHostState.showSnackbar(message = "你\"確定\"就好。")
}
title.value = ""
message.value = ""
}) {
Text(text = "確認")
}
},
dismissButton = {
TextButton(onClick = {
showAlertDialog.value = false
scope.launch {
snackbarHostState.showSnackbar("你開心\"取消\"也沒關係。")
}
}) {
Text(text = "取消")
}
}
)
}
}
}
}
示範畫面:
參考資料:https://developer.android.com/jetpack/compose/components/dialog?hl=zh-tw
發佈留言