3

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?

San
  • 64
  • 1
  • 6
  • 1
    You can use `TextFieldValue`. Please, check if this answer helps you https://stackoverflow.com/questions/68244362/select-all-text-of-textfield-in-jetpack-compose/68245465#68245465 – nglauber Jun 29 '22 at 23:15
  • @nglauber 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. – San Jun 30 '22 at 08:33
  • you can use VisualTransformation & OffsetMapping. https://medium.com/@banmarkovic/how-to-create-currency-amount-input-in-android-jetpack-compose-1bd11ba3b629 – Arpit Patel Jul 19 '22 at 18:49

1 Answers1

3

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.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • 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. – San Jun 30 '22 at 08:30
  • 2
    @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`. – CommonsWare Jun 30 '22 at 11:41
  • 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! – San Jun 30 '22 at 13:24