我正在尝试使用 Jetpack compose 在 Android 中创建一个完全自定义的 TextField
硬件键盘一切正常,但软键盘打不开
我就是这样开始的: (用简单的代码)
@Composable
fun MyCustomTextField() {
var text by remember { mutableStateOf("") }
val focusRequester = remember { FocusRequester() }
val keyboardController = LocalSoftwareKeyboardController.current
var hasFocus by remember { mutableStateOf(false) }
Box(
modifier = Modifier
.focusRequester(focusRequester)
.onFocusChanged { hasFocus = it.hasFocus }
.focusable()
.focusTarget()
.clickable {
// Request focus and show keyboard when clicked
if (!hasFocus) {
focusRequester.requestFocus()
} else {
keyboardController?.show()
}
}
.onKeyEvent {
if (it.type == KeyEventType.KeyDown) {
if (it.nativeKeyEvent.keyCode == KeyEvent.KEYCODE_DEL) {
if (text.isNotEmpty()) {
text = text.substring(0, text.length - 1)
}
} else {
text += it.nativeKeyEvent.unicodeChar
.toChar()
.toString()
}
}
false
}
)
{
Text("text:" + text)
}
// Request focus when the composable enters the composition
LaunchedEffect(hasFocus) {
focusRequester.requestFocus()
keyboardController?.show()
}
}
我已根据需要进行更改以集中注意力。
试试这个代码:
@Composable
fun MyCustomTextField() {
var text by remember { mutableStateOf("") }
val focusRequester = remember { FocusRequester() }
val keyboardController = LocalSoftwareKeyboardController.current
var hasFocus by remember { mutableStateOf(false) }
Box(
modifier = Modifier
.focusRequester(focusRequester)
.onFocusChanged { focusState -> hasFocus = focusState.hasFocus }
.focusable()
.clickable {
// Request focus and show keyboard when clicked
if (!hasFocus) {
focusRequester.requestFocus()
} else {
keyboardController?.show()
}
}
.onKeyEvent {
if (it.type == KeyEventType.KeyDown) {
if (it.nativeKeyEvent.keyCode == KeyEvent.KEYCODE_DEL) {
if (text.isNotEmpty()) {
text = text.substring(0, text.length - 1)
}
} else {
text += it.nativeKeyEvent.unicodeChar
.toChar()
.toString()
}
}
false
}
) {
Text(text = "text: $text")
}
// Request focus and show keyboard when the composable enters the composition
LaunchedEffect(hasFocus) {
if (hasFocus) {
keyboardController?.show()
}
}
}