当我以编程方式隐藏专注于文本字段的键盘时,它会闪烁。如何摆脱这个?
val keyboardController = LocalSoftwareKeyboardController.current
var text by rememberSaveable { mutableStateOf("") }
TextField(
modifier = Modifier.fillMaxWidth(),
value = text,
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
keyboardActions = KeyboardActions(
onDone = {
keyboardController?.hide() // Causes flickering
}
),
onValueChange = {
text = it
}
)
我还注意到,当您打开上一个屏幕时,有时会出现闪烁。是否可以在某个地方看到到底是什么导致键盘打开和关闭?
POCO X3 NFC、Android 12、MIUI Global 14.0.2
androidx.compose:compose-bom:2023.08.00
您可以在组合感知范围内运行隐藏操作,因此它将在文本字段的重新组合后继续存在。这应该可以防止您现在看到的闪烁:
val keyboardController = LocalSoftwareKeyboardController.current
val scope = rememberCoroutineScope()
var text by rememberSaveable { mutableStateOf("") }
TextField(
modifier = Modifier.fillMaxWidth(),
value = text,
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
keyboardActions = KeyboardActions(
onDone = {
scope.launch { // make use of a composition-aware scope
keyboardController?.hide()
}
}
),
onValueChange = {
text = it
}
)
另一种选择是使用
FocusManager
,并清除文本字段中的焦点,这也会隐藏键盘。选择取决于您是否要删除文本字段的焦点。