Android Jetpack Compose: Can't set backgroundColor for OutlinedTextField

Issue

I’m new to Jetpack Compose, and trying to set backgroundColor to an OutlinedTextField.

This is my code

fun MyTextField() {
    Column(Modifier
        .background(Color.Gray)
        .fillMaxSize()
        .padding(8.dp)
    ) {
        OutlinedTextField(
            value = "text",
            onValueChange = {},
            colors = TextFieldDefaults.outlinedTextFieldColors(
                backgroundColor = Color.White, // does not work
                unfocusedBorderColor = Color.Red,
                textColor = Color.Red
            ),
            // modifier = Modifier.background(Color.White) - works but not as I expected
        )
    }
}

The backgroundColor = Color.White does not work at all. The OutlinedTextField stays transparent:

When using the modifier the background is changed, but also the part reserved for Label, even when I don’t have a label:

Any ideas what am I doing wrong? Thank you.

Solution

I’ll leave my answer here because I didn’t find an easier way…

You can define a composable which will work as wrapper+background.

@Composable
fun OutlinedTextFieldBackground(
    color: Color,
    content: @Composable () -> Unit
) {
    // This box just wraps the background and the OutlinedTextField
    Box {
        // This box works as background
        Box(
            modifier = Modifier
                .matchParentSize()
                .padding(top = 8.dp) // adding some space to the label
                .background(
                    color, 
                    // rounded corner to match with the OutlinedTextField
                    shape = RoundedCornerShape(4.dp) 
                )
        )
        // OutlineTextField will be the content...
        content()
    }
}

Then you just need to wrap your OutlinedTextField with it.

OutlinedTextFieldBackground(Color.LightGray) {
    OutlinedTextField(
        modifier = Modifier.fillMaxWidth(),
        value = textState.value,
        onValueChange = { textState.value = it },
        label = {
            Text(
                text = "Name"
            )
        },
    )
}

Here is the result:
enter image description here

As you can see, it works. But as mentioned by Sergey Krivenkov it could be a bad choice in terms of design, because half of the label has one background and other part has another background and this could looks strange.

Answered By – nglauber

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published