Search code examples
androidkotlinandroid-jetpack-composeandroid-jetpack

How to get rid of the external white background of RoundedCornerShape


I'm trying to make a little indicator light- text in a rounded rectangle where the background of the rounded rectangle changes depending on indicator state and the rest of the background is either black or transparent. I'm finding that the external corners of the shape are filled in with what seems to be a default white colour and not the colour of the containing object's background.

In this example, by my understanding, every background should be either green, blue or red. The white bits in the image shouldn't be there. Does anyone know what's wrong? I'm running Android Studio 2020.3.1 patch 3

. enter image description here

fun IndicatorLight() {
 
    Surface(modifier = Modifier.padding(4.dp)
        .background(Color.Green)) {
        Box(
            modifier = Modifier
                .clip(RoundedCornerShape(20.dp))
                .background(Color.Red)
                .padding(3.dp)
        ) {
            Box(
                modifier = Modifier
                    .padding(4.dp)
                    .background(Color.Blue)
            ) {
                Text(
                    text = text,
                    style = TextStyle(
                        color = foreground,
                        fontWeight = FontWeight.Bold,
                        fontSize = 24.sp
                    )
                )
            }
        }
    }
}

Solution

  • The surface has already a property named color to change the background color.

    So change your code like this

    Surface(
        color = Color.Green
    ) {}
    

    Remove that padding from the surface and give it into the box if you want that Box to get 4.dp padding from the surface. And yeah modifier order is important so be careful about that. I have given padding before and after the background so that you can test by removing or reducing those padding how it's working.

    You can change your full code like the one below

    Surface(
        color = Color.Green
    ) {
        Box(
            modifier = Modifier
                .padding(5.dp)
                .clip(RoundedCornerShape(20.dp))
                .background(Color.Red)
                .padding(5.dp)
        ) {
            Box(
                modifier = Modifier
                    .padding(5.dp)
                    .background(Color.Blue)
                    .padding(5.dp)
            ) {
                Text(
                    text = "Text",
                    style = TextStyle(
                        color = Color.White,
                        fontWeight = FontWeight.Bold,
                        fontSize = 24.sp
                    )
                )
            }
        }
    }
    

    You will get this.

    result