Card in Jetpack Compose

Card in Jetpack Compose: A Comprehensive Guide

In Android development, CardView is a popular UI element for displaying content in a card-like layout with rounded corners, shadow effects, and a clean, elevated appearance. With Jetpack Compose, this concept is implemented using the Card composable, which provides similar functionality but with a more declarative and functional approach to building UIs.

This article will dive deep into the Card composable in Jetpack Compose, explaining how to use it, customize it, and create rich, interactive cards with various content.


What is the Card Composable?

The Card composable in Jetpack Compose is a UI element used to display content in a card-like container with shadow effects and rounded corners. It is often used for displaying a block of content, like an item in a list or a piece of information, such as a profile, product, or article.

The Card composable provides a simple way to add an elevated UI element with a background, padding, and rounded corners to your app.

Basic Usage of Card in Jetpack Compose

A simple Card in Jetpack Compose can be created with the Card composable. You can add text, images, icons, and other components inside the Card for richer content.

Example: Basic Card

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.text.BasicText
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp

@Composable
fun SimpleCard() {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(16.dp),
        elevation = CardDefaults.elevation(8.dp)
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            Text("Card Title", style = MaterialTheme.typography.titleMedium)
            Spacer(modifier = Modifier.height(8.dp))
            Text("This is the content of the card. You can add more elements here.")
        }
    }
}

@Preview(showBackground = true)
@Composable
fun PreviewSimpleCard() {
    SimpleCard()
}

Breakdown of the Code:

  1. Card Composable: The Card composable is the main container that wraps the content. It takes in parameters like modifier and elevation. The elevation defines the shadow around the card, which creates a 3D effect.
  2. Modifier: We use Modifier.fillMaxWidth() to make the card take the full width of the screen and Modifier.padding(16.dp) to add padding around the card.
  3. Padding Inside the Card: Inside the Card, we use a Column to arrange text vertically and add padding around the content for better readability.
  4. Elevation: The elevation parameter adds a shadow effect beneath the card, enhancing its visual appeal.

Customizing the Card Appearance

The Card composable in Jetpack Compose comes with several customization options to style and tweak its appearance. Here are some of the key parameters:

1. Background Color:

You can customize the background color of the Card using the colors parameter.

Card(
    modifier = Modifier.padding(16.dp),
    colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.primary),
    elevation = CardDefaults.elevation(8.dp)
) {
    // Card content
}

2. Shape:

The shape parameter allows you to control the roundness of the card’s corners. You can use RoundedCornerShape to create rounded corners.

Card(
    modifier = Modifier.padding(16.dp),
    shape = RoundedCornerShape(12.dp),
    elevation = CardDefaults.elevation(8.dp)
) {
    // Card content
}

3. Border:

You can add borders to the card by using the border modifier in the Card.

Card(
    modifier = Modifier
        .padding(16.dp)
        .border(1.dp, Color.Gray, RoundedCornerShape(8.dp)),
    elevation = CardDefaults.elevation(8.dp)
) {
    // Card content
}

Adding Interactive Content to Cards

Cards can also be interactive. You can wrap any content inside the Card with clickable modifiers, allowing users to interact with the card, for example, to navigate or trigger actions.

Example: Clickable Card

@Composable
fun ClickableCard(onClick: () -> Unit) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(16.dp)
            .clickable { onClick() },
        elevation = CardDefaults.elevation(8.dp)
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            Text("Click Me!", style = MaterialTheme.typography.h6)
            Spacer(modifier = Modifier.height(8.dp))
            Text("Tap on this card to trigger an action.")
        }
    }
}

In the above example, the Card becomes clickable using the clickable modifier. When tapped, the onClick lambda function is invoked, allowing you to handle the action, such as navigating to another screen.


Using Card for Lists: LazyColumn and LazyRow

Cards are often used inside lists to display content dynamically. You can easily use a Card in combination with LazyColumn or LazyRow for displaying scrollable content.

Example: Cards in a LazyColumn

@Composable
fun CardList() {
    LazyColumn {
        items(10) { index ->
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(8.dp),
                elevation = CardDefaults.elevation(8.dp)
            ) {
                Column(
                    modifier = Modifier.padding(16.dp)
                ) {
                    Text("Card Title #$index", style = MaterialTheme.typography.h6)
                    Spacer(modifier = Modifier.height(8.dp))
                    Text("This is the content of card #$index.")
                }
            }
        }
    }
}

In this example, we use LazyColumn to display a list of cards. Each item in the list is wrapped in a Card, with the content changing dynamically based on the index.


Card with Images and Text

Cards are frequently used to display a combination of images and text. Jetpack Compose allows you to easily combine different UI elements within a card.

Example: Card with Image and Text

import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp

@Composable
fun CardWithImage() {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(16.dp),
        shape = RoundedCornerShape(16.dp),
        elevation = CardDefaults.elevation(8.dp)
    ) {
        Column {
            Image(
                painter = painterResource(id = R.drawable.sample_image),
                contentDescription = "Sample Image",
                modifier = Modifier
                    .fillMaxWidth()
                    .height(180.dp),
                contentScale = ContentScale.Crop
            )
            Spacer(modifier = Modifier.height(8.dp))
            Text(
                text = "Card with Image and Text",
                modifier = Modifier.padding(16.dp),
                style = MaterialTheme.typography.h6
            )
            Text(
                text = "This is a card that contains both an image and text.",
                modifier = Modifier.padding(horizontal = 16.dp),
                style = MaterialTheme.typography.body1
            )
        }
    }
}

@Preview(showBackground = true)
@Composable
fun PreviewCardWithImage() {
    CardWithImage()
}

In this example:

  1. The Card contains an image and some text.
  2. We use the Image composable to display an image inside the card, using ContentScale.Crop to crop the image while maintaining its aspect ratio.
  3. The Column composable is used to arrange the image and text vertically inside the card.

Conclusion

The Card composable in Jetpack Compose provides a flexible and easy way to implement card-like UI elements with customizable styling, elevation, and interaction. Whether you are displaying simple text, images, or a combination of both, Card makes it easier to create visually appealing, interactive, and organized content.

With its ability to integrate seamlessly into lists (LazyColumn/LazyRow) and its rich customization options, the Card composable is an essential UI building block for any Compose-based app.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top