androidandroid-jetpack-composematerial3

Changing card elevation is changing card color in Jetpack compose with Material 3


I am using the Card composable and I want it to be colored white.

But when I add some elevation to it, it changes color to more like the primaryContainer color.

I have seen documentation where they have somehting called as elevationOverlay. But couldn't find an example which says how to use it.

Here is my code:

Card(
      modifier = Modifier.padding(top = 16.dp),
      colors = CardDefaults.cardColors(containerColor = White),
      elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
) {
}

I do know I can use Elevated card instead of card, but there is same problem with elevated card as well.

Also, this is a special case so I am applying the color manually


Solution

  • After trying multiple ways found out that there is no way to override this except for to look at the Card.kt file from SDK and create something similar but disable the tonalColor(Thanks for hint @ianhanniballake that it is using tonalelevation)

    Following code should do the work, until overriding is officially supported:

    @Composable
    fun CardWithoutTonalElevation(
        modifier: Modifier = Modifier,
        shape: Shape = CardDefaults.shape,
        colors: Color = White,
        border: BorderStroke? = null,
        elevation: Dp = 0.dp,
        content: @Composable ColumnScope.() -> Unit = {}
    )  {
        Surface(
            modifier = modifier,
            shape = shape,
            color = colors,
            tonalElevation = 0.dp,
            shadowElevation = elevation,
            border = border,
        ) {
            Column(content = content)
        }
    }