Jetpack Compose: How to use Card

Introduction

Jetpack Compose is rapidly transforming the way Android developers build user interfaces by offering a declarative approach to UI development. Instead of the traditional XML-based layouts, Jetpack Compose allows developers to create dynamic, flexible UIs using Kotlin code. Among the numerous UI components available, the Card component stands out as a versatile and visually appealing way to display content. It can be used to create sections of a screen that are visually distinct, adding both structure and emphasis.

In this article, we will explore how to use the Card component in Jetpack Compose by breaking down an example Kotlin code snippet. This will help you understand how to apply various properties like background color, borders, padding, and text styling to create a clean, modern UI. Whether you're a seasoned developer or new to Compose, you'll find useful insights on how to enhance your app’s design with the Card widget.

Understanding the Structure

The starting point of the example is the MainActivity class, which extends AppCompatActivity. Here, we utilize the setContent function to initialize the composable content. This function sets up the entire screen using Jetpack Compose, replacing the need for a traditional XML layout file. By directly invoking MainContent, we jump right into rendering our custom-designed card on the screen. This is a great demonstration of how Jetpack Compose simplifies UI creation, making it more intuitive and less verbose.

The MainContent composable function is where the primary logic of our card resides. The Card component is used here with several properties to customize its appearance. It uses the Modifier to control its size and padding, ensuring it occupies most of the screen width but with some space around its edges. The use of fillMaxWidth(.95F) ensures that the card adjusts to 95% of the screen's width, creating a balanced layout that avoids a cramped look.

Customizing the Card Appearance

The Card component in this example is set with a backgroundColor property set to yellow, providing a bright, eye-catching background. Additionally, we’ve added an elevation of 8.dp to give the card a slight shadow, making it appear raised above the background surface. This is particularly useful when you want to highlight a specific section of your app. The shape attribute is defined using MaterialTheme.shapes.medium, which ensures that the card corners have a medium-rounded effect, aligning with Material Design guidelines.

One of the most striking features of the card is the red border added using the BorderStroke class. By setting a thickness of 3.dp, the card gains a bold outline that adds contrast and helps it stand out. This border is particularly useful if you want to differentiate the card from other elements on the screen or emphasize its content. With these properties, the card becomes a customizable container that can adapt to various design needs.

Styling the Text Inside the Card

Inside the Card component, we have a Text composable that displays a simple message: "I am a Card." The text is styled to be large and prominent with a font size of 35.sp, making it easily readable. We have applied bold font weight and a sans-serif font family to give it a modern, clean look. The FontStyle.Normal is used here, but it can be adjusted to italic or other styles if needed for different design aesthetics.

Moreover, the text alignment is set to TextAlign.Center, ensuring that the text is centered within the card. The color of the text is set to blue, creating a pleasant contrast against the yellow background. To prevent the text from appearing too close to the card's edges, a padding of 25.dp is applied, adding white space around the content. This use of padding and alignment demonstrates how Jetpack Compose makes it easy to achieve precise control over the layout and design of your components.

Previewing the Composable

To preview the card without having to run the app on an emulator or physical device, the ComposablePreview function is included. Although currently commented out in the provided code, this function can be uncommented to see a real-time preview of the MainContent in Android Studio. Utilizing the @Preview annotation allows developers to quickly visualize their designs and make adjustments on the fly. This feature is particularly helpful during the design phase, speeding up the development process.

Summary

In conclusion, the example demonstrates how to leverage the Card component in Jetpack Compose to create visually appealing and functional UI elements. By combining various properties such as background color, elevation, borders, and text styling, you can build cards that enhance the user experience of your app. The flexibility of the Card component allows developers to create both simple and complex designs, making it an essential tool in modern Android development.

Jetpack Compose simplifies the way we approach UI design, allowing developers to create and preview components in real-time. As seen in the example, implementing a Card component is straightforward yet powerful, providing a solid foundation for creating sophisticated layouts in your applications. Whether you're designing a dashboard, a list of items, or any section that needs emphasis, the Card widget can help you achieve a polished look with minimal effort.


MainActivity.kt

package com.cfsuman.jetpackcompose

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            MainContent()
        }
    }


    @Composable
    fun MainContent(){
        Card(
            Modifier
                .fillMaxWidth(.95F)
                .padding(15.dp),
            backgroundColor = Color.Yellow,
            elevation = 8.dp,
            shape = MaterialTheme.shapes.medium,
            border = BorderStroke(3.dp, Color.Red),
        ) {
            Text(
                text = "I am a Card.",
                fontSize = 35.sp,
                fontStyle = FontStyle.Normal,
                fontWeight = FontWeight.Bold,
                fontFamily = FontFamily.SansSerif,
                modifier = Modifier
                    .padding(25.dp),
                textAlign = TextAlign.Center,
                color = Color.Blue
            )
        }
    }


    @Preview
    @Composable
    fun ComposablePreview(){
        //MainContent()
    }
}
More android jetpack compose tutorials