Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

When should I use Android Jetpack Compose Surface composable?

There's 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. When should I use the Surface composable and what the benefits it gives me?

question from:https://stackoverflow.com/questions/65918835/when-should-i-use-android-jetpack-compose-surface-composable

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Surface composable makes the code easier as well as explicitly indicates that the code uses a material surface. Let's see an example:

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

and the result:

enter image description here

The same result can be achieved without 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)
)

but it has a few drawbacks:

  • The modifiers chain is pretty big and it isn't obvious that it implements a material surface
  • I have to declare a variable for the shape and pass it into three different modifiers
  • It uses contentColorFor to figure out the content color while Surface does it under the hood. As a result the backgroundColor is used in two places as well.
  • I have to calculate the elevation in pixels
  • Surface adjusts colors for elevation (in case of dark theme) according to the material design. If you want the same behavior, it should be handled manually.

For the full list of Surface features it's better to take a look at the documentation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...