我正在使用Jetpack Compose TextField
,并且当用户按下操作按钮(imeActionPerformed
参数)时,我想关闭虚拟键盘。
val text = +state { "" }
TextField(
value = text.value,
keyboardType = KeyboardType.Text,
imeAction = ImeAction.Done,
onImeActionPerformed = {
// TODO Close the virtual keyboard here <<<
}
onValueChange = { s -> text.value = s }
)
答案 0 :(得分:16)
从撰写版本 1.0.0-alpha12(在 beta08 中有效)起,onImeActionPerformed
已被弃用,建议的方法是将 keyboardActions
与 keyboardOptions
结合使用:
val focusManager = LocalFocusManager.current
OutlinedTextField(
value = ...,
onValueChange = ...,
label = ...,
keyboardActions = KeyboardActions(onDone = { focusManager.clearFocus() }),
keyboardOptions = KeyboardOptions.Default.copy(imeAction = ImeAction.Done, keyboardType = KeyboardType.Password),
)
focusManager.clearFocus()
将负责关闭软键盘。
答案 1 :(得分:4)
通过1.0.0-alpha01
,您可以使用SoftwareKeyboardController
类:
var text by remember { mutableStateOf(TextFieldValue("Text")) }
TextField(
value = text,
onValueChange = {
text = it
},
label = { Text("Label") },
imeAction = ImeAction.Done,
onImeActionPerformed = { action, softwareController ->
if (action == ImeAction.Done) {
softwareController?.hideSoftwareKeyboard()
}
}
)
答案 2 :(得分:1)
在 1.0.0
中,您可以使用 SoftwareKeyboardController
或 FocusManager
来执行此操作。
这个答案侧重于他们的差异。
var text by remember { mutableStateOf("")}
TextField(
value = text,
onValueChange = { text = it },
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
keyboardActions = KeyboardActions(onDone = { /* TODO */ }),
)
基于 @Gabriele Mariottis
的回答。
val keyboardController = LocalSoftwareKeyboardController.current
// TODO =
keyboardController?.hide()
这只会关闭键盘,但不会清除任何聚焦的 TextField 的焦点(注意粗下划线)。
基于 @azizbekians
的回答。
val focusManager = LocalFocusManager.current
// TODO =
focusManager.clearFocus()
这会关闭键盘并清除 TextField 的焦点。
答案 3 :(得分:0)
我找到了解决方法here:)
fun hideKeyboard(activity: Activity) {
val imm: InputMethodManager = activity.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
var view = activity.currentFocus
if (view == null) {
view = View(activity)
}
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
我只需要从我的组件中调用以上函数:
// getting the context
val context = +ambient(ContextAmbient)
// textfield state
val text = +state { "" }
TextField(
value = text.value,
keyboardType = KeyboardType.Text,
imeAction = ImeAction.Done,
onImeActionPerformed = {
if (imeAction == ImeAction.Done) {
hideKeyboard(context as Activity)
}
}
onValueChange = { s -> text.value = s }
)
答案 4 :(得分:0)
要添加 Gabriele Mariotti's solution,如果您想有条件地隐藏键盘,例如在单击按钮后,请使用:
keyboardController?.hide()
例如,点击添加按钮后隐藏键盘:
var newWord by remember { mutableStateOf("") }
val keyboardController = LocalSoftwareKeyboardController.current
// Setup the text field with keyboard as provided by Gabriele Mariotti
...
Button(
modifier = Modifier
.height(56.dp),
onClick = {
if (!newWord.trim().isNullOrEmpty()) {
wordViewModel.onAddWord(newWord.trim())
newWord = ""
keyboardController?.hide()
}
...