简体   繁体   English

在 Jetpack Compose with Material 3 中更改卡片高度会更改卡片颜色

[英]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.我正在使用 Card 可组合项,我希望它是白色的。

But when I add some elevation to it, it changes color to more like the primaryContainer color.但是当我向它添加一些高度时,它会将颜色更改为更像 primaryContainer 颜色。

I have seen documentation where they have somehting called as elevationOverlay.我看过文档,其中有一些称为 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.我知道我可以使用 Elevated 卡代替卡,但是 elevated 卡也有同样的问题。

Also, this is a special case so I am applying the color manually此外,这是一个特殊情况,所以我手动应用颜色

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.要解决使用 Material Design 3 在 Jetpack Compose 中修改卡片高度时更改卡片颜色的问题,您可以使用背景修改器并将其传递给颜色 object 以设置所需的颜色。 Additionally, you can use the elevationOverlay parameter to set the overlay color.此外,您可以使用 elevationOverlay 参数来设置叠加颜色。

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
) {}

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)在尝试了多种方法后发现除了查看 SDK 中的 Card.kt 文件并创建类似的东西但禁用 tonalColor 之外没有办法覆盖它(感谢 @ianhanniballake 提示它正在使用 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)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM