0

I want to get position (x, y) of current cursor when the user is typing in a BasicTextField. The BasicTextField is expandable and can cover full screen.

I need it to display suggestion list just on top of the written text

Something like this that follows TextField cursor

enter image description here

Oussèma Hassine
  • 741
  • 1
  • 7
  • 18

1 Answers1

0

This is my solution using a BasicTextField.

I'm using a TextFieldValue to keep the TextField string value and cursor position (accessible via selection field).
This value is updated within the onValueChange{} callback.

The two values we are looking for will be stored in cursorYCoord and cursorXCoord

In order to get cursorYCoord, we need to get first the cursorLine.
cursorXCoord is obtained within the onTextLayout callback

var textFieldValue by remember {
    mutableStateOf(TextFieldValue(description))
}
var textLayoutResult by remember {
    mutableStateOf<TextLayoutResult?>(null)
}
val cursorLine by remember {
    derivedStateOf { textLayoutResult?.getLineForOffset(textFieldValue.selection.start) ?: 0 }
}
val cursorYCoord by remember {
    derivedStateOf { (textLayoutResult?.getLineBottom(cursorLine) ?: 0f).toInt() }
}
var cursorXCoord by remember {
    mutableStateOf(0)
}


BasicTextField(
   [...]
   onValueChange = {
        textFieldValue = it
    },
    onTextLayout = {
        textLayoutResult = it

        cursorXCoord = it.getHorizontalPosition(textFieldValue.selection.start, true).toInt()
    },
   [...]
Gio
  • 190
  • 2
  • 11