How to set the cursor to any part of the text using TextFieldValue (w/ FocusRequester) on pressing/clicking the TextField

229 Views Asked by At

I tried to look around but I can't find a way to

  • force a focus,

  • set the cursor to the end of text

  • and still be able to set the cursor to any part of the text when pressing/clicking.

With FocusRequester the cursor is set to the start of text, but with TextFieldValue(<text>, <range>) I'm able to place the cursor at the end, the problem is that with this approach the cursor is always forced to any specified selection = TextRange(<index>)(in my case its the end using the current length of the changing value onValueChange), I have no idea how to set the cursor in any part (selection) when I press/click the TextField.

My Implementation:

var textFieldValue by remember { mutableStateOf(TextFieldValue("Some Text")) }

    Row (
        modifier = Modifier
            .height(150.dp)
            .fillMaxWidth()
            .clickable {
                focusRequester.requestFocus()
                textFieldValue = textFieldValue.copy(selection = TextRange("Some Text".length))
            }
    ) {

        BasicTextField(
            modifier = Modifier.focusRequester(focusRequester),
            value = textFieldValue,
            onValueChange = {
                textFieldValue =
                    textFieldValue.copy(text = it.text, selection = TextRange(it.text.length))
            },
        )
    }

And what I'm trying to achieve (Large text area with text set and starts from top-left), its entire part should be clickable and triggers focus for the text field, the reason why I wrapped it in a Row with a clickable modifier.

enter image description here

enter image description here

I wasn't able to achieve this with a single text field with specified height, as TextAlign doesn't have a Top-Start alignment

0

There are 0 best solutions below