Jetpack Compose TextField 捕获键盘 Enter-input

问题描述 投票:0回答:2

据我了解,Jetpack Compose Textfield 有一个用于捕获键盘操作的 API,但我不知道这个 API 有哪些可以捕获 Enter-Input

此捕获 Enter 输入的用例是启用单击 Enter 并尝试转到下一个 TextField 并保持同时保持键盘打开

OutlinedTextField(
    value = username.value,
    onValueChange = {
        username.value = it
        },
    keyboardActions = KeyboardActions(
        onDone = {},
        onGo = {},
        onNext = {},
        onPrevious ={},
        onSearch ={},
        onSend = {}
        )
)
android kotlin android-jetpack-compose textfield android-compose-textfield
2个回答
29
投票

你可以使用类似的东西:

val (focusRequester) = FocusRequester.createRefs()

TextField(
    value = text,
    onValueChange = {
        text = it
    },
    singleLine = true,
    keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
    keyboardActions = KeyboardActions(
        onDone = { focusRequester.requestFocus() }
    ),
    modifier = Modifier.onKeyEvent {
        if (it.nativeKeyEvent.keyCode == KeyEvent.KEYCODE_ENTER){
            focusRequester.requestFocus()
            true
        }
        false
    }
)

TextField(
    value = text2,
    onValueChange = {
        text2 = it
    },
    modifier = Modifier.focusRequester(focusRequester),
)

0
投票

适用于带有 KMP 的 Windows / 桌面平台

你需要

                singleLine = true,
                modifier = Modifier.onKeyEvent { event ->
                    return@onKeyEvent if (event.key.keyCode == Key.Enter.keyCode){
                        viewModel.login(userName, userName)
                        true
                    } else {
                        false
                    }
                }

示例

           TextField(
                value = userName,
                onValueChange = { userName = it },
                label = { Text("Username") },
                keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
                keyboardActions = KeyboardActions(onDone = {
                    viewModel.login(userName, userName)
                }),
                singleLine = true,
                modifier = Modifier.onKeyEvent { event ->
                    return@onKeyEvent if (event.key.keyCode == Key.Enter.keyCode){
                        viewModel.login(userName, userName)
                        true
                    } else {
                        false
                    }
                }
            )
© www.soinside.com 2019 - 2024. All rights reserved.