我什么时候应该使用 Android Jetpack Compose Surface 可组合项?
When should I use Android Jetpack Compose Surface composable?
有Surface composable in Jetpack Compose which represents a material surface. A surface allows you to setup things like background color or border but it seems that the same might be done using modifiers。我应该什么时候使用 Surface 可组合项以及它给我带来的好处?
Surface composable makes the code easier as well as explicitly indicates that the code uses a material surface。让我们看一个例子:
Surface(
color = MaterialTheme.colors.primarySurface,
border = BorderStroke(1.dp, MaterialTheme.colors.secondary),
shape = RoundedCornerShape(8.dp),
elevation = 8.dp
) {
Text(
text = "example",
modifier = Modifier.padding(8.dp)
)
}
结果:
不用Surface也能得到同样的结果:
val shape = RoundedCornerShape(8.dp)
val shadowElevationPx = with(LocalDensity.current) { 2.dp.toPx() }
val backgroundColor = MaterialTheme.colors.primarySurface
Text(
text = "example",
color = contentColorFor(backgroundColor),
modifier = Modifier
.graphicsLayer(shape = shape, shadowElevation = shadowElevationPx)
.background(backgroundColor, shape)
.border(1.dp, MaterialTheme.colors.secondary, shape)
.padding(8.dp)
)
但它有一些缺点:
- 修饰符链相当大,它实现了一个 material 表面
并不明显
- 我必须为形状声明一个变量并将其传递给三个不同的修饰符
- 它使用 contentColorFor 来计算内容颜色,而 Surface 在后台执行。因此
backgroundColor
也用在两个地方。
- 我必须以像素为单位计算高程
Surface
调整高度的颜色(在深色主题的情况下)according to the material design。如果您想要相同的行为,则应手动处理。
有关 Surface 功能的完整列表,最好查看 documentation。
Surface 相当于视图系统中的 CardView
。
通过Surface
,您可以设置视图的高度(注意这与Modifier.shadow不同)
有Surface composable in Jetpack Compose which represents a material surface. A surface allows you to setup things like background color or border but it seems that the same might be done using modifiers。我应该什么时候使用 Surface 可组合项以及它给我带来的好处?
Surface composable makes the code easier as well as explicitly indicates that the code uses a material surface。让我们看一个例子:
Surface(
color = MaterialTheme.colors.primarySurface,
border = BorderStroke(1.dp, MaterialTheme.colors.secondary),
shape = RoundedCornerShape(8.dp),
elevation = 8.dp
) {
Text(
text = "example",
modifier = Modifier.padding(8.dp)
)
}
结果:
不用Surface也能得到同样的结果:
val shape = RoundedCornerShape(8.dp)
val shadowElevationPx = with(LocalDensity.current) { 2.dp.toPx() }
val backgroundColor = MaterialTheme.colors.primarySurface
Text(
text = "example",
color = contentColorFor(backgroundColor),
modifier = Modifier
.graphicsLayer(shape = shape, shadowElevation = shadowElevationPx)
.background(backgroundColor, shape)
.border(1.dp, MaterialTheme.colors.secondary, shape)
.padding(8.dp)
)
但它有一些缺点:
- 修饰符链相当大,它实现了一个 material 表面 并不明显
- 我必须为形状声明一个变量并将其传递给三个不同的修饰符
- 它使用 contentColorFor 来计算内容颜色,而 Surface 在后台执行。因此
backgroundColor
也用在两个地方。 - 我必须以像素为单位计算高程
Surface
调整高度的颜色(在深色主题的情况下)according to the material design。如果您想要相同的行为,则应手动处理。
有关 Surface 功能的完整列表,最好查看 documentation。
Surface 相当于视图系统中的 CardView
。
通过Surface
,您可以设置视图的高度(注意这与Modifier.shadow不同)