How to change text field cursor position in jetpack compose

We can use TextFieldValue to change cursor position

Initialise the TextFieldValue just like this

 var textFieldValueState by remember {
        mutableStateOf(
            TextFieldValue(
                text = ""
            )
        )
    }

after initialising it set the TextFieldValue just like the below

OutlinedTextField(
    value = textFieldValueState,
    onValueChange = { textFieldValueState = it },
    ...
    )

To append additional text and for cursor selection, follow these steps

IconButton(modifier = Modifier.then(Modifier.size(48.dp)),
     onClick = {
        val value = textFieldValueState.text.plus("****")
        textFieldValueState = TextFieldValue(
        text = value,
        selection = TextRange(value.length-2)
        )
     })

reference image

TextFieldValue text and selection variables are not changeable so we need to create new TextFieldValue to set the text and cursor position.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)