How to get cursor position for TextField (Jetpack Compose)?
Asked Answered
F

1

6

For a regular EditText, we can get the cursor position by calling the getSelectionStart() method. In Jetpack Compose this posibility is available for ClickableText, but apparently not for TextField or OutlinedTextField.

Has anyone come across this problem and know how to solve it?

Feel answered 29/6, 2022 at 22:59 Comment(3)
You can use TextFieldValue. Please, check if this answer helps you #68244862Ralph
@Ralph Unfortunately no, I know how to add a selection to a TextField, but I want to know how to get the cursor position (offset) by clicking the text in the TextField.Feel
you can use VisualTransformation & OffsetMapping. medium.com/@banmarkovic/…Obligato
G
5

For a regular EditText, we can get the cursor position by calling the getSelectionStart() method

That is because EditText is stateful.

In Jetpack Compose this posibility is available for ClickableText, but apparently not for TextField or OutlinedTextField.

Composables are stateless.

Has anyone come across this problem and know how to solve it?

In the case of BasicTextField() and related composables, use the composable where your state is TextFieldValue. Then, the selection property of the TextFieldValue has a TextRange that you can use to get the cursor position.

Guam answered 29/6, 2022 at 23:21 Comment(3)
Thanks for the answer, but apparently this is not what I need. I want to get the offset position by clicking a TextField (or an OutlinedTextField, for example). I know that TextFieldValue has a select property, but it won't help to get the cursor position by clicking the text in the TextField.Feel
@San: The documentation for selection has "If the selection is collapsed, it represents cursor location". That seems to be as relevant for your case as getSelectionStart() would be with EditText.Guam
Yes, you're right. I've checked the TextFieldValue.selection.start by clicking the text and it contains the current cursor position. Thank you very much!Feel

© 2022 - 2024 — McMap. All rights reserved.