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()
},
[...]