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

Time:01-31

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

CodePudding user response:

To resolve the issue of changing card color when modifying the card elevation in Jetpack Compose with Material Design 3, you can use the background modifier and pass it a Color object to set the desired color. Additionally, you can use the elevationOverlay parameter to set the overlay color.

Here's an updated example of your code:

Card(
  modifier = Modifier.padding(top = 16. dp)
  .background(color = Color.White),
  elevation = CardDefaults.cardElevation(defaultElevation = 2. dp),
  elevationOverlay = Color.White
) {}

CodePudding user response:

You can use the elevationOverlay property to specify the color that will be used to fill the area under the card's shadow. By default, this color is the same as the background color of the card. To set the elevationOverlay color to white, you can try this.

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

CodePudding user response:

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)
    }
}
  • Related