Jetpack compose ui : How to create cardview?

Viewed 9815

I want to create Cardview using jetpack compose but i am not able to find any example.

enter image description here

3 Answers

With 1.0.0 you can use something like:

Card(
    shape = RoundedCornerShape(8.dp),
    backgroundColor = MaterialTheme.colors.surface,
) {
    Column(
        modifier = Modifier.height(200.dp).padding(16.dp),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ){
        Text(text = "This is a card view",
            style = MaterialTheme.typography.h4)
    }
}

enter image description here


With Material3 you can use:

Card(
   shape = RoundedCornerShape(8.dp),
   colors = CardDefaults.cardColors(containerColor = /* ... */)
)

in v0.1.0-dev09 version, can be done like this, where the padding of Card sets the margin of the card, the padding of Box sets the padding inside the card.

Card(
  shape = RoundedCornerShape(8.dp), 
  modifier = Modifier.padding(16.dp).fillMaxWidth()
) {
  Box(modifier = Modifier.height(200.dp).padding(16.dp)) {
    Text("This is a card view")
  }
}

enter image description here

As the friends recommended, Card is a way of creating CardView but you can do that by surface too :

val shape = RoundedCornerShape(10.dp)
Surface(modifier = Modifier.size(250.dp, 70.dp), elevation = 8.dp, shape = shape) {
      Text(text = "Sample text")
}

Note that Surface and Card cannot be used for positioning items so that if you wanna position that Text(text = "Sample text") , you should use one layout inside that Surface like this :

val shape = RoundedCornerShape(10.dp)
Surface(modifier = Modifier.size(250.dp, 70.dp), elevation = 8.dp, shape = shape) {
    Box(modifier = Modifier.fillMaxSize()) {
          Text(modifier = Modifier.align(Alignment.Center), text = "Sample text")
    }
}

The appropriate way for creating CardView is this but if you wanna just create shadow for a view, you can use Modifier.shadow (Note that Modifier.shadow and Surface/Card are not the same):

Box(modifier = Modifier.size(250.dp, 70.dp).shadow(8.dp, RoundedCornerShape(10.dp)), contentAlignment = Alignment.Center) {
        Text(text = "Sample Text")
}
Related