androidandroid-jetpack-composeandroid-cardviewandroid-compose-card

Card VS Box render Difference


Is there an explanation for why this

Card(
        modifier =
        Modifier
            .background(
                brush = Brush.horizontalGradient(
                    colors = listOf(
                        OrgFarmTheme.colors.secondary,
                        OrgFarmTheme.colors.onSecondary
                    )
                )
            )
           .clip(RoundedCornerShape(10))
    ) {
...
}

renders this,

while

Box(
        modifier =
        Modifier
            .background(
                brush = Brush.horizontalGradient(
                    colors = listOf(
                        OrgFarmTheme.colors.secondary,
                        OrgFarmTheme.colors.onSecondary
                    )
                )
            )
            .clip(RoundedCornerShape(10))
    ) {
...
}

renders this ?

I have tried using the default shape parameter of the Card, but it renders the same.


Solution

  • The Card background color is defined by the backgroundColor property and not by the background modifier. This property also has a default value = MaterialTheme.colors.surface which is applied by default to the Card. It is the reason of the difference in your code.

    If you want to achieve with the Card the same layout of the Box you have to use:

    Card(
        modifier =
        Modifier
            .background(
                brush = Brush.horizontalGradient(
                    colors = listOf(
                        MaterialTheme.colors.secondary,
                        MaterialTheme.colors.onSecondary
                    )
                )
            )
            ,
        backgroundColor =  Transparent,
        shape = RoundedCornerShape(10),
        elevation = 0.dp //it is important to avoid borders
    )
    

    If you want a Box with elevation and a gradient as background you can use the shadow modifier:

    Box(
        modifier =
        Modifier
            .shadow(12.dp,RoundedCornerShape(10),true)
            .background(
                brush = Brush.horizontalGradient(
                    colors = listOf(
                        MaterialTheme.colors.secondary,
                        MaterialTheme.colors.onSecondary
                    )
                )
            )
            .clip(RoundedCornerShape(10))
    ) {
    }
    

    enter image description here