我們可以在 Android 中有一個對話框監聽器:
dialog.setOnKeyListener(new Dialog.OnKeyListener() {
@Override
public boolean onKey(DialogInterface arg0, int keyCode,KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK) {
/* The user pressed back button - do whatever here.
Normally you dismiss the dialog like dialog.dismiss(); */
}
return true;
}
});
我們如何AlertDialog在 Jetpack Compose 中做到這一點?
@Composable
private fun DisplayAlertDialog() {
val openDialog = remember { mutableStateOf(true) }
if (openDialog.value) {
AlertDialog(
onDismissRequest = { },
title = {
Text(
text = stringResource(id = R.string.settings),
fontSize = 18.sp
)
},
confirmButton = {
TextButton(
onClick = {
openDialog.value = false
}
) {
Text(stringResource(id = R.string.yes))
}
},
dismissButton = {
TextButton(
onClick = {
openDialog.value = false
}
) {
Text(stringResource(id = R.string.no))
}
},
backgroundColor = Color.White,
contentColor = Color.Black
)
}
}
uj5u.com熱心網友回復:
在此答案中查看Modifier.onKeyEvent用法的詳細資訊。
在這種情況下requestFocus,必須從內部呼叫AlertDialog以確保它已經出現。
在我的示例中,我使用一個文本欄位來顯示修改器沒有被中斷。
var displayed by remember { mutableStateOf(true) }
if (displayed) {
val requester = remember { FocusRequester() }
AlertDialog(
onDismissRequest = {
println("dismissOnClickOutside")
displayed = false
},
buttons = {
var text by remember { mutableStateOf("") }
TextField(value = text, onValueChange = {text = it})
LaunchedEffect(Unit) {
requester.requestFocus()
}
},
properties = DialogProperties(
dismissOnBackPress = false,
),
modifier = Modifier
.focusRequester(requester)
.focusable()
.onKeyEvent {
if (it.nativeKeyEvent.keyCode != KeyEvent.KEYCODE_BACK) {
return@onKeyEvent false
}
println("dismissOnBackPress")
displayed = false
false
}
)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/325937.html
標籤:安卓 科特林 android-jetpack-compose
