'Request Focus on TextField in jetpack compose

How to auto focus on textfield in jetpack compose. When i click on textfield and start typing on it. Meantime when i click back button,then when i'm try to click on textfield, nothing happens.

val textState = remember { mutableStateOf(TextFieldValue()) }
TextField(
    modifier = Modifier.fillMaxWidth(),
    value = textState.value,
    onValueChange = { value : TextFieldValue ->
        textState.value = value
    }
)


Solution 1:[1]

Posting an updated Answer to the question (APIs were renamed in Compose Beta)

@Composable
fun AutoFocusingText() {
    var value by mutableStateOf("Enter Text")
    val focusRequester = remember { FocusRequester() }
    TextField(
        value = value, 
        onValueChange = { value = it },
        modifier = Modifier.focusRequester(focusRequester)
    )
    
    LaunchedEffect(Unit) {
        focusRequester.requestFocus()
    }
}

Solution 2:[2]

With 1.0.x you can use something like:

var text by remember { mutableStateOf("text") }

// initialize focus reference to be able to request focus programmatically
val focusRequester = FocusRequester()

Column {
    TextField(
        value = text,
        onValueChange = {
            text = it
        },
        label = { Text("label") },
        modifier = Modifier
            // add focusRequester modifier 
            .focusRequester(focusRequester)
    )

Then use focusRequester.requestFocus(). In this way the system grants focus to the component associated with this FocusRequester.

To have the field automatically focused when the screen appears you can use:

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

To manually grant the focus to the field:

    Button(onClick = { focusRequester.requestFocus() }) {
        Text("Click to give the focus")
    }

Solution 3:[3]

val focusRequester = remember { FocusRequester() }
val inputService = LocalTextInputService.current
val focus = remember { mutableStateOf(false) }
BasicTextField(
    value = "value",
    modifier = Modifier
        .height(40.dp)
        .fillMaxWidth()
        .focusRequester(focusRequester)
        .onFocusChanged {
            if (focus.value != it.isFocused) {
                focus.value = it.isFocused
                if (!it.isFocused) {
                    inputService?.hideSoftwareKeyboard()
                }
            }
        },
),

LaunchedEffect("") {
    delay(300)
    inputService?.showSoftwareKeyboard()
    focusRequester.requestFocus()
}

Solution 4:[4]

Taken from Compose Unit Tests and applied to TextField Link

    @ExperimentalFocus
    @Composable
    fun AutoFocusingText() {
        val textState = remember { mutableStateOf(TextFieldValue()) }
        val focusState = remember { mutableStateOf(FocusState.Inactive) }
        val focusRequester = FocusRequester()
        val focusModifier = Modifier.focus()
        Row(
            modifier = Modifier.focusObserver { focusState.value = it }
        ) {
            val focusRequesterModifier = Modifier.focusRequester(focusRequester)
            TextField(
                modifier = focusModifier.then(focusRequesterModifier),
                value = textState.value,
                onValueChange = { value: TextFieldValue ->
                    textState.value = value
                },

                )
        }
        onActive {
            focusRequester.requestFocus()
        }
    }

Edit: Changed Box to Row because Box has been deprecated in '1.0.0-alpha04'

Solution 5:[5]

If you wanted your text field to be focused automatically when you navigate to the screen, you can use this. This allows you not to requestFocus during composition which is not something you should do. Otherwise, you will get IllegalStateException with the message "FocusRequester is not initialized" at times.

 @Composable fun YourComposable(){ 
   val focusRequester = remember {FocusRequester()}
    
        LaunchedEffect(Unit) {
            this.coroutineContext.job.invokeOnCompletion {
                focusRequester.requestFocus()
            }
        }
    
       OutlinedTextField( modifier = Modifier.focusRequester(focusRequester))
         
              
}

This is due to the coroutine inside LaucnhedEffeect will be canceled when the LaunchedEffect leaves the composition.

Solution 6:[6]

` @Composable fun SomeComposable() { val focusRequester = remember { FocusRequester() }

OutlinedTextField(
    value = TextFieldValue(
    text = state.text, // state come from else where
    selection = TextRange(state.text.length,state.text.length)),  

    onValueChange = { _:TextFieldValue -> Unit },
    modifier = Modifier
      .fillMaxWidth()
      .focusRequester(focusRequester),)

SideEffect {
    focusRequester.requestFocus()
    }
}

`

Why SideEffect: https://developer.android.com/reference/kotlin/androidx/compose/runtime/package-summary#SideEffect(kotlin.Function0) the very first line of docs.
For Cursor Position that what helped: https://stackoverflow.com/a/65565502/6813176
onValueChanged left as is in my working code, have no need for it.

Solution 7:[7]

move cursor to the length of the text, and allow user to move cursor on TextField with following code

 @Composable
    fun AutoFocusingText(value:String,onValueChange: (newValue: String) -> Unit) {
    var textFieldValueState by remember { mutableStateOf(TextFieldValue(text = value,selection = TextRange(value.length))) }
    val textFieldValue = textFieldValueState.copy(text = value)
    val focusRequester = FocusRequester()
    DisposableEffect(Unit) {
        focusRequester.requestFocus()
        onDispose { }
    }
    TextField(
        value = textFieldValue,
        onValueChange = {
            textFieldValueState = it
            if (value != it.text) {
                onValueChange(it.text)
            } },
        modifier = Modifier.focusRequester(focusRequester = focusRequester)
    )


}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 vovahost
Solution 2
Solution 3 Abhimanyu
Solution 4
Solution 5
Solution 6 zxxz
Solution 7 Mohd Qasim