Make Text Selectable using the Mouse

989 Views Asked by At

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.

1

There are 1 best solutions below

0
vovahost On

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,
}