2

I want to make the Text selectable using the mouse similar to the TextField.

SelectionContainer {
  Text(
    text = "Some very long text which can be selected by Mouse Left Press and drag to the right.",
    maxLines = 1,
    textAlign = TextAlign.Start,
  )
}

It works but when I try to select the entire content, by moving the mouse to the right edge of the text, it doesn't scroll the text automatically, similar to what a TextField would do.

Using a TextField works perfectly but its initial state is: Text scrolled horizontally to the end. Instead I want it to display the start.

TextField(
  value = "Some very long text which can be selected by Mouse Left Press and drag to the right.",
  maxLines = 1,
  singleLine = true,
  readOnly = true,
  onValueChange = {},
)

I can achieve what I want using Modifier.horizontalScroll(rememberScrollState(0)) but then it breaks the text selection. I can only select the visible text using the mouse. It doesn't scroll automatically the text field when selecting with the mouse.

vovahost
  • 34,185
  • 17
  • 113
  • 116
  • Just tried your second example - text stays at the start for me. And can easily select by moving mouse to the right edge. – Kiryl Tkach Oct 14 '22 at 23:02
  • @KirylTkach Set the text field to have a limited width, and then set the initial text to exceed the available field width to reproduce this. – vovahost Oct 16 '22 at 09:47

1 Answers1

0

What worked was to set the selection = TextRange.Zero:

var textFieldValue by rememberSaveable(stateSaver = TextFieldValue.Saver) {
    mutableStateOf(TextFieldValue(text = text, selection = TextRange.Zero))
}

BasicTextField(
    value = textFieldValue,
    textStyle = textStyle.copy(
      color = LocalContentColor.current,
    ),
    onValueChange = {},
    readOnly = true,
}
vovahost
  • 34,185
  • 17
  • 113
  • 116