https://kotlinlang.org logo
#compose
Title
# compose
d

Dirk Hoffmann

10/23/2023, 2:07 PM
Hi, I want to keep track of the cursor position in a
BasicTextField
. Everything works fine except, when I tap/click somewhere inside the TextField text, it (for sure) changes the position of the cursor, but as no text change or layout change is happening to the TextField content, I cannot update my cursor position. I have TextLayoutResult as a remembered state to get the new cursor rect via
TextLayoutResult.getCursorRect(textFieldValue.selection.end.coerceAtMost(layoutInput.text.length))
how can I get the cursor rect when I change it via "just clicking somewhere else" inside the TextFields text?
z

Zach Klippenstein (he/him) [MOD]

10/23/2023, 4:42 PM
Use the
TextFieldValue
overload to get the position of the cursor, then use the layout result to calculate its coordinates
d

Dirk Hoffmann

10/23/2023, 5:25 PM
hmmm, could you elaborate a bit more, please? Not totally clear what you mean. (a) if I "click" somewhere in the text, NO .clickable(...) or .onClick() neither .pointerInput(Unit) { ... } will be called. (b) IF I somehow manage to get a click "recognized", how can I get the cursor rect out of the
TextFieldValue
???
ok, think you meant
TextLayoutResult
(and not TextFieldValue) ... so (b) would be an ugly line like:
Copy code
val cursorRect = textLayoutResult.value?.multiParagraph?.getCursorRect(textFieldValue.selection.end.coerceAtMost(textLayoutResult.value?.multiParagraph?.intrinsics?.annotatedString?.text?.length ?: 0).coerceAtLeast(0)) ?: Rect.Zero
            println("cursorRect in onClick: $cursorRect")
leaves me with problem (a) I just don't get any click/tab working for
BasicTextField
. Any ideas on that?? @Zach Klippenstein (he/him) [MOD]
z

Zach Klippenstein (he/him) [MOD]

10/23/2023, 9:07 PM
If you want to track any time the cursor changes, use
TextFieldValue
and observe it for selection changes. If you specifically only want to track clicks, then use
TextFieldValue
and a pointerInput gesture to peek at pointer events.