我正在使用 Kotlin 和 Compose 创建适用于 Android(特别是 Wear OS)的自定义键盘。
按下键盘内的按钮时如何隐藏键盘?
在 Wear OS 中打字时,键盘占据整个屏幕,因此我认为需要该按钮。 预先感谢您!
我已经尝试过这个,但没有隐藏键盘:
val imeService = IMEService()
val inputConnection = LocalSoftwareKeyboardController.current?.let
{
imeService.currentInputConnection
}
inputConnection?.finishComposingText()
inputConnection?.sendKeyEvent(
KeyEvent(
KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_ENTER
)
)
inputConnection?.performEditorAction(EditorInfo.IME_ACTION_GO)
inputConnection?.performEditorAction(EditorInfo.IME_ACTION_DONE)
inputConnection?.closeConnection()
imeService.hideKeyboard(view)
如何正确地将文本提交到文本字段?
您尝试一起使用 IMEService 和 LocalSoftwareKeyboardController 似乎混合了不以您所描述的方式直接交互的概念。相反,您应该专注于使用 LocalSoftwareKeyboardController 来控制键盘的可见性。
@Composable
fun CustomKeyboardWithButton() {
val keyboardController = LocalSoftwareKeyboardController.current
val focusRequester = remember { FocusRequester() }
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
// Your keyboard UI here
Button(onClick = {
// Assuming you have a way to get the current input connection
// and it's stored in a variable named `inputConnection`
inputConnection?.finishComposingText()
inputConnection?.sendKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER))
inputConnection?.performEditorAction(EditorInfo.IME_ACTION_GO)
inputConnection?.performEditorAction(EditorInfo.IME_ACTION_DONE)
inputConnection?.closeConnection()
keyboardController?.hide()
}) {
Text("Hide Keyboard")
}
}
}
关于正确将文本提交到文本字段,您通常可以通过 TextField 可组合项的 onValueChange 参数来处理此问题。这是一个简单的例子:
@Composable
fun TextFieldWithCommitExample() {
var text by remember { mutableStateOf("") }
TextField(
value = text,
onValueChange = { newText ->
text = newText
// Commit the text to the underlying input connection here
// This might involve using the InputConnection to send the text
},
modifier = Modifier.focusRequester(focusRequester)
)
}
如果有帮助请告诉我:D