Search code examples
android-jetpack-composematerial-components-android

Android Native Jetpack Compose OutlinedTextField Selected By Default


In Android Native Jetpack Compose, using the material androidx.compose.material3.OutlinedTextField composable, is there some way to cause the default value I put in the field to be selected as soon as the field gets focus? Right now the cursor in the field is at the end of the data, so that if the user wants to change the default, they have to delete the old data, and then replace it. If the data in the field was already selected when the screen is rendered, the user could just type the new value to replace the entire default contents of the field.

I’m not seeing any parameters of the object that seem to do what I’d need. I’m wondering if there is some other way to accomplish this.


Solution

  • You need to pass the cursor value when you set the Initial value to the TextField

    Output: preview

    This is how you can make your text selected.

    @Composable
    fun OutLineTextFieldAutoSelected() {
    
        val text = "Default Value"
    
        val searchTextFieldValue =
            remember { mutableStateOf(TextFieldValue(text)) }
    
        Column(modifier = Modifier.padding(15.dp)) {
            OutlinedTextField(
                value = searchTextFieldValue.value,
                modifier = Modifier
                    .fillMaxWidth()
                    .onFocusChanged { state ->
                        if (state.hasFocus) {
                            searchTextFieldValue.value = searchTextFieldValue.value.copy(
                                selection = TextRange(
                                    0,
                                    searchTextFieldValue.value.text.length
                                )
                            )
                        }
                    },
                onValueChange = {
                    searchTextFieldValue.value = it
                },
                shape = RoundedCornerShape(12.dp),
                singleLine = true,
                colors = OutlinedTextFieldDefaults.colors(
                    cursorColor = Color.Black,
                    focusedBorderColor = Color.Black,
                    unfocusedBorderColor = Color.Black,
                ),
                placeholder = {
                    Text(
                        text = "Enter your text",
                        modifier = Modifier
                            .fillMaxWidth(),
                        style = TextStyle(
                            fontSize = 14.sp,
                            color = Color.LightGray
                        )
                    )
                },
                keyboardOptions = KeyboardOptions.Default.copy(
                    keyboardType = KeyboardType.Text,
                    autoCorrect = true,
                ),
            )
        }
    }