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

3.4k Views Asked by At

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?

1

There are 1 best solutions below

3
CommonsWare On

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.