导航到jetpack compose中的可组合时如何自动请求焦点到文本字段

时间:2021-07-06 10:07:06

标签: android android-jetpack-compose

我希望当用户导航到可组合时,键盘通过自动请求焦点在 jetpack compose 中的文本字段上弹出。截至目前,这是我尝试过的,但似乎不起作用

val feedbackContent = remember { mutableStateOf(TextFieldValue()) }
val focusRequester = remember { FocusRequester() }

OutlinedTextField(
                modifier = Modifier
                    .clickable {
                        focusRequester.requestFocus()
                    }
                    .fillMaxWidth()
                    .focusRequester(focusRequester)
                    .focusable()
)

1 个答案:

答案 0 :(得分:3)

您可以使用以下内容:

val focusRequester = FocusRequester()
val keyboardController = LocalSoftwareKeyboardController.current

OutlinedTextField(
    value = text,
    onValueChange = { text = it},
    modifier = Modifier
        .fillMaxWidth()
        .focusRequester(focusRequester)
        .onFocusChanged {
            if (it.isFocused) {
                keyboardController?.show()
            }
        }
)

DisposableEffect(Unit) {
    focusRequester.requestFocus()
    onDispose { }
}