android-jetpack-composeandroid-jetpack-compose-text

How to change text field cursor position in jetpack compose


I have list of text suggestions chip view above textfield, when user clicking chip I am appending the text into textfield. after that I want to move the cursor to the end position. I couldn't find solution for this in Jetpack compose. earlier we used editText.setSelection(position) to change cursor position in android views.

How to set a cursor position in jetpack compose Textfield?

         OutlinedTextField(
                    value = value,
                    onValueChange = { value = it },
                    maxLines = 8,
                    label = {
                        Text(
                            text = "Content",
                            maxLines = 1
                        )
                    },

                    modifier = Modifier
                        .fillMaxWidth()
                        .height(200.dp),
                    shape = RoundedCornerShape(2.dp),

                    )

Solution

  • 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.