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?

3
  • 1
    You can use TextFieldValue. Please, check if this answer helps you stackoverflow.com/questions/68244362/… Commented Jun 29, 2022 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. Commented Jun 30, 2022 at 8:33
  • you can use VisualTransformation & OffsetMapping. medium.com/@banmarkovic/… Commented Jul 19, 2022 at 18:49

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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: 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.
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!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.