TextField selection initialization problem

81 views Asked by At

I have a textField, I initialize its value to zero when the application starts, and the first time I click on the field, the cursor moves to position 0 instead of 1

val state = rememberSaveable { mutableStateOf(TextFieldValue("0", TextRange(1))) }
    
TextField(
    value = state.value,
    keyboardOptions = KeyboardOptions(
        keyboardType = KeyboardType.Decimal
    ),
    onValueChange = { state.value = it }
)

The problem goes away if you leave onValueChange empty, since I understand that when textField is initialized, it sends the value where the cursor is TextRange.Zero. Isn't this a bad effect?

The solution that I have found so far is to initialize the state with a delay, but this is a crutch and not a solution.

What are the solutions?

1

There are 1 answers

0
Abhishek Tiwari On

Adding this modifier fixes the issue.

modifier = Modifier.height(IntrinsicSize.Max)

See Why does the cursor always appear at the start of my OutlinedTextField?

var textFieldValue by rememberSaveable(
                        stateSaver = TextFieldValue.Saver
                    ) {
                        mutableStateOf(
                            TextFieldValue(text = "0", selection = TextRange(1))
                        )
                    }

                    Box(
                        modifier = Modifier
                            .fillMaxSize(),
                        contentAlignment = Alignment.Center
                    ) {
                        TextField(
                            modifier = Modifier.height(IntrinsicSize.Max),
                            value = textFieldValue,
                            keyboardOptions = KeyboardOptions(
                                keyboardType = KeyboardType.Decimal
                            ),
                            onValueChange = { newTextFieldValueState ->
                                textFieldValue = newTextFieldValueState
                            }
                        )
                    }