androidandroid-jetpack-composeandroid-compose-textfield

How to auto request focus to a text field when navigated to a composable in jetpack compose


I want the keyboard to pop up by an auto requesting focus on a text field in jetpack compose when the user navigates to a composable. As of now, this is what I have tried but it doesn't seem to work

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

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

Solution

  • You can use something like:

    val focusRequester = remember { FocusRequester() }
    val keyboardController = LocalSoftwareKeyboardController.current
    
    OutlinedTextField(
        value = text,
        onValueChange = { text = it},
        modifier = Modifier
            .fillMaxWidth()
            .focusRequester(focusRequester)
            .onFocusChanged {
                if (it.isFocused) {
                    keyboardController?.show()
                }
            }
    )
    
    LaunchedEffect(Unit) {
        focusRequester.requestFocus()
    }