0

If we want our TextField to have an equivalent behaviour to EditText:selectAllOnFocus = "true" we can do something like create a TextFieldValue and set the selection from zero to lenght like TextRange(0, text.length)

This works and when user focus the TextField the whole text get selected, the problem is that when we create a TextFieldValue we need to set selection, the default value is Zero.

If the user wants to drag the cursor he just cant. Is there a way for now to create a selectAllOnFocus behaviour that allows the user to drag the cursor all over the text if he wants to in compose?

Ivan Regados
  • 61
  • 1
  • 5

1 Answers1

1

Yes I think one way is to follow the result selection coming from the TextField onValueChange callback:

var editableText by rememberSaveable { mutableStateOf("some text") }
val textRangeStart = rememberSaveable { mutableStateOf(0) }
val textRangeEnd = rememberSaveable { mutableStateOf(0) }
val textField = remember(editableText, textRangeEnd.value, textRangeStart.value) {
    mutableStateOf(
        TextFieldValue(
            text = editableText ?: "",
            selection = TextRange(textRangeStart.value, textRangeEnd.value)
        )
    )
}
TextField(
        modifier = Modifier.fillMaxSize(),
        value = textField.value,
        placeholder = { Text("") },
        onValueChange = {
            textEditorViewModel.editableText.value = it.text
            textRangeStart.value = it.selection.start
            textRangeEnd.value = it.selection.end
        }
    )
}
zjmo
  • 625
  • 2
  • 8