I have text in a textfield, but when I use IMEActi...
# compose
g
I have text in a textfield, but when I use IMEAction next to go to this textfield, the cursor is in front of the text. Does someone know which property I can use to change it.
s
You need to use the
TextFieldValue
to set selection, you can do it like this
Copy code
@Composable
fun SlackDemo() {
    val focusRequester = remember { FocusRequester() }
    var textFieldValue by remember { mutableStateOf(TextFieldValue("an editable string")) }
    Column {
        TextField(
            value = textFieldValue,
            onValueChange = { textFieldValue = it },
            modifier = Modifier.focusRequester(focusRequester)
        )
        Button(onClick = {
            focusRequester.requestFocus()
            val endSelection = TextRange(textFieldValue.text.length)
            textFieldValue = textFieldValue.copy(selection = endSelection)
        }) {
            Text("Set focus");
        }
    }
}
Also feel free to extend TextField with some helpers like:
Copy code
sealed class CursorPosition {
    object Start: CursorPosition()
    object End: CursorPosition()
    data class Cursor(val loc: Int): CursorPosition()
    data class Selection(val start: Int, val end: Int): CursorPosition()
}

/**
 * Some useful ways to select
 */
fun TextFieldValue.copyWithCursorPosition(cursorPosition: CursorPosition): TextFieldValue {
    return when(cursorPosition) {
        CursorPosition.Start -> copy(selection = TextRange(0))
        CursorPosition.End -> copy(selection = TextRange(text.length))
        is CursorPosition.Cursor -> copy(
            selection = TextRange(cursorPosition.loc.coerceIn(0..text.length))
        )
        is CursorPosition.Selection -> copy(
            selection = TextRange(
                start = cursorPosition.start.coerceIn(0..text.length),
                end = cursorPosition.end.coerceIn(0..text.length)
            )
        )
    }
}
so app code becomes something like:
Copy code
Button(onClick = {
            focusRequester.requestFocus()
            textFieldValue = textFieldValue.copyWithCursorPosition(CursorPosition.End)
        }) {
            Text("Set focus");
        }