Jetpack Compose: How to make a Card clickable

Introduction

In Android app development, creating interactive UI elements is essential for enhancing user experience. Jetpack Compose, Android’s modern toolkit for building native UI, offers developers a declarative way to design interfaces with reactive components. One common task in UI design is making components clickable, such as displaying a counter that updates on tap or click. In Jetpack Compose, implementing click behavior is streamlined and straightforward, allowing you to control how elements respond to user interactions with minimal boilerplate.

This article explains how to create clickable cards in Jetpack Compose. In the example code, we build two cards that react differently when clicked: one card increments a counter when tapped, and the other decrements it. By following this breakdown, you’ll gain a solid understanding of how to use Jetpack Compose to handle user interactions and dynamically update the UI.

Code Breakdown: Main Activity Setup

The entry point of the app is the MainActivity class, which extends AppCompatActivity. Within the onCreate method, the setContent function is used to define the app’s content. Here, setContent is called with the GetScaffold composable function, which initializes the app's main screen layout. This setup reflects the flexibility of Jetpack Compose, as it allows the UI to be defined directly within Kotlin functions rather than XML.

The GetScaffold function wraps the app’s UI within a Scaffold composable, which is designed to handle basic UI structure components like the top bar, bottom bar, floating action buttons, and more. In this case, the Scaffold includes a TopAppBar that displays the title “Compose - Card Clickable” with a background color. Additionally, the main content of the screen is set to the MainContent composable, defining the core interactive elements.

Main Content Structure

The MainContent function is where the primary UI elements are organized. Inside, a Column composable is used to structure the layout vertically. This Column is set to take up the entire screen size with fillMaxSize, and it includes padding around the edges for visual spacing. By specifying Arrangement.SpaceEvenly, the child elements within the Column are spaced evenly, providing a balanced layout. horizontalAlignment is set to Alignment.CenterHorizontally, ensuring the elements are aligned in the center of the screen horizontally.

A mutable state variable counter is created using remember and mutableStateOf. This variable tracks the count displayed in the cards, and its value is updated in response to user interactions. Using remember allows the state to persist across recompositions, so the counter value is retained as users interact with the app.

First Card: Incrementing the Counter

The first Card composable is styled with a background color, elevation, and rounded corners. It spans the full width of the screen, with a fixed height of 150 dp. The clickable modifier is applied to this card, which defines the interaction behavior when the card is tapped. Inside the clickable block, the counter variable is incremented by one each time the card is clicked.

Inside the card, a Box composable is used to center a Text composable, which displays the current value of counter. This is an example of Jetpack Compose’s flexibility, as UI components and data are tightly integrated. Whenever the counter value changes, Jetpack Compose automatically re-composes the UI, updating the displayed count in real-time without any manual intervention.

Second Card: Decrementing the Counter

The second Card is similar in layout and style to the first but demonstrates an alternative method for handling clicks. Instead of using the clickable modifier, this card uses the pointerInput modifier combined with the detectTapGestures function to manage touch gestures. This approach offers more customization for tap events, as it allows for separate gesture detection, including long-press, double-tap, and more. In this case, onTap is defined to decrement the counter by one each time the card is tapped.

This card has a red background color to visually distinguish it from the first. By using pointerInput with detectTapGestures, the code showcases how to go beyond basic clicks and implement more advanced gesture recognition in Jetpack Compose. This flexibility is particularly useful in scenarios where you want to provide custom interactions beyond simple clicks.

Preview Function

The ComposablePreview function serves as a preview setup, allowing developers to view the UI within Android Studio’s preview pane. Although commented out in this code, invoking GetScaffold() inside ComposablePreview would enable a visual preview of the app’s main screen without needing to run the app on an emulator or physical device. This feature is extremely useful for speeding up the UI design process.

Summary

This example demonstrates how to create interactive cards in Jetpack Compose by utilizing modifiers like clickable and pointerInput to handle user interactions. Jetpack Compose’s declarative UI approach simplifies state management and reactivity, making it easier for developers to design responsive interfaces. With just a few lines of code, it’s possible to create complex behavior, such as updating a counter in real-time based on user clicks.

Whether you’re building a simple counter or a more complex app, understanding how to handle click events and manage state in Jetpack Compose is essential. This example serves as a foundational pattern for building interactive elements, illustrating the flexibility and power of Jetpack Compose in creating modern Android applications.


MainActivity.kt

package com.cfsuman.jetpackcompose

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp

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

        setContent {
            GetScaffold()
        }
    }


    @Composable
    fun GetScaffold(){
        Scaffold(
            topBar = {TopAppBar(
                title = {Text(
                    "Compose - Card Clickable",
                    color = Color.White)},
                backgroundColor = Color(0xFF58427C)) },
            content = {MainContent()},
            backgroundColor = Color(0xFFEDEAE0)
        )
    }


    @Composable
    fun MainContent(){
        var counter by remember { mutableStateOf(0)}

        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(12.dp),
            verticalArrangement = Arrangement.SpaceEvenly,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {

            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(150.dp)
                    .clickable{
                        counter ++
                    },
                backgroundColor = Color(0xFF319177),
                elevation = 4.dp,
                shape = RoundedCornerShape(24.dp),
            ) {
                Box(Modifier.wrapContentSize(Alignment.Center)) {
                    Text(
                        text = "$counter",
                        style = MaterialTheme.typography.h1
                    )
                }
            }

            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(150.dp)
                    .pointerInput(UInt){
                        detectTapGestures(
                            onTap = { counter-- }
                        )
                    },
                backgroundColor = Color(0xFFE95C4B),
                elevation = 4.dp,
                shape = RoundedCornerShape(24.dp),
            ) {
                Box(Modifier.wrapContentSize(Alignment.Center)) {
                    Text(
                        text = "$counter",
                        style = MaterialTheme.typography.h1
                    )
                }
            }
        }
    }


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

jetpack compose - Card alignment

Compose Card Content Alignment
The Card is a widget of the jetpack compose library. A Card layout displays a single widget inside it. The Card is useful to render a specified shape with elevation. The Card also can draw a background color on its surface. The jetpack compose developer can put a border/stroke around the Card layout itself. But how can they align the content inside of a Card layout?

By default, the Card widget constructor has no argument to directly set alignment for its child element. So we have to write extra code to define the alignment of a Card child. The following jetpack compose tutorial will demonstrate to us how we can set a Card content alignment in an android application.

The Box is another layout widget of the android jetpack compose library. We can set alignment for the Box content using its constructor’s ‘contentAlignment’ argument.

The Card widget tries to expand its child size to fill the parent Card size. To align the Card content, we have to wrap the Card child element with a Box widget to define its position inside the Card layout. The alignment of the Box child element will act as the Card content alignment.

The default value of the Box ‘contentAlignment’ argument is ‘Alignment.TopStart’. There are many available values for the ‘contentAlignment’ argument such as Alignment.Center, Alignment.TopEnd, Alignment.BottomStart, Alignment.CenterStart, etc. Those names are self-describing. So, if we want to put an element at the exact center of the Box layout (practically Card layout), then we can simply pass the ‘contentAlignment’ argument value to ‘Alignment.Center’.

This jetpack compose tutorial code written in an android studio IDE. Copy the code and run it on an emulator device or a real device to test how we define the Card layout content alignment. We also displayed a screenshot of this tutorial’s emulator screen at the bottom of this tutorial.
MainActivity.kt

package com.cfsuman.jetpackcompose

import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp

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

        setContent {
            GetScaffold()
        }
    }


    @SuppressLint("UnusedMaterialScaffoldPaddingParameter")
    @Composable
    fun GetScaffold(){
        Scaffold(
            topBar = {TopAppBar(
                title = {Text(
                    "Compose - Card Alignment",
                    color = Color.White)},
                backgroundColor = Color(0xFF58427C)) },
            content = {MainContent()},
            backgroundColor = Color(0xFFEDEAE0)
        )
    }


    @Composable
    fun MainContent(){
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(12.dp),
            verticalArrangement = Arrangement.SpaceEvenly,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(150.dp),
                backgroundColor = Color(0xFFE95C4B),
                elevation = 4.dp,
                shape = RoundedCornerShape(24.dp),
            ) {
                Box(contentAlignment = Alignment.Center) {
                    Text(
                        text = "Card Alignment Center",
                        style = MaterialTheme.typography.h6
                    )
                }
            }

            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(150.dp),
                backgroundColor = Color(0xFFE95C4B),
                elevation = 4.dp,
                shape = RoundedCornerShape(24.dp),
            ) {
                Box(
                    Modifier.padding(12.dp),
                    contentAlignment = Alignment.BottomStart
                ) {
                    Text(
                        text = "Card Alignment Bottom",
                        style = MaterialTheme.typography.h6
                    )
                }
            }

            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(150.dp),
                backgroundColor = Color(0xFFE95C4B),
                elevation = 4.dp,
                shape = RoundedCornerShape(24.dp),
            ) {
                Box(
                    Modifier.padding(12.dp),
                    contentAlignment = Alignment.TopEnd
                ) {
                    Text(
                        text = "Card Alignment End",
                        style = MaterialTheme.typography.h6
                    )
                }
            }
        }
    }


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

Jetpack Compose: How to add Card background color

Introduction

In Android development, Jetpack Compose offers a modern toolkit for building native UI using a declarative approach. This toolkit simplifies the UI creation process by enabling developers to define UI components directly within the code, making layout and design easier to implement and customize. One of the frequently used UI elements in Jetpack Compose is the Card component, which allows you to organize content in a visually appealing way. By leveraging color, shape, and background customizations, developers can create engaging cards that enhance the user experience.

This example demonstrates how to create two custom-styled Card components in Jetpack Compose. The first card has a solid background color, while the second card showcases a gradient background achieved through the Brush.radialGradient function. This example also utilizes Scaffold, a high-level layout component, to add a top app bar and handle the screen’s overall background color, making it easier to maintain a consistent theme throughout the app.

Code Breakdown

The MainActivity class serves as the entry point of the application. In its onCreate method, the setContent function is used to define the UI hierarchy by calling the GetScaffold composable function. This function acts as the main layout container for the app and includes a Scaffold component. The Scaffold component provides a structured layout with built-in support for elements like top app bars, bottom navigation, floating action buttons, and more.

Inside the GetScaffold composable, the TopAppBar component creates a custom app bar at the top of the screen. This app bar has a title text reading "Compose - Card Background Color," with a white text color on a custom purple background (defined by the hex color 0xFF58427C). The Scaffold itself has a light beige background (0xFFEDEAE0), which sets the primary color theme for the screen. The main content of the screen is managed by another composable function, MainContent.

The MainContent composable is responsible for displaying the core layout, using a Column to align and organize the cards vertically. The Column component fills the screen with a padding of 12dp and centers its children horizontally. Inside the column, two Card composables are created, each demonstrating a different approach to background styling.

The first card showcases a solid background color. This card fills the width of the screen with a height of 175dp, a rounded corner shape of 24dp, and a light pink background color (0xFFFFBCD9). Within this card, a Box composable adds padding around a Text element, which displays "Card Solid Background" in a headline font style.

The second card introduces a more dynamic background using a radial gradient. This card also fills the width of the screen and has the same height and rounded corner properties as the first card. Instead of a solid color, the card's background is set to transparent, allowing for a custom gradient to be applied. The background modifier in the Box component uses Brush.radialGradient to create a multi-colored radial gradient that blends from light orange to pink to light blue. Inside the box, a Text element displays the message "Card Gradient Background," showing how flexible background styling can enhance a card's visual appeal.

Summary

This example demonstrates how Jetpack Compose allows developers to customize Card backgrounds using both solid colors and gradient effects. The use of Scaffold to define a structured layout and TopAppBar to add a title showcases how Compose streamlines UI development in Android by reducing the need for XML layouts and simplifying styling through modifiers. By controlling the color, shape, and padding of each Card, the example highlights the versatility of Jetpack Compose in creating visually distinctive UI components.

In essence, Jetpack Compose's declarative approach allows for creative and flexible UI designs with minimal code, offering a powerful alternative to traditional Android UI development. This example provides a starting point for Android developers who want to experiment with background customization in their own Compose applications.


MainActivity.kt

package com.cfsuman.jetpackcompose

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp

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

        setContent {
            GetScaffold()
        }
    }


    @Composable
    fun GetScaffold(){
        Scaffold(
            topBar = {TopAppBar(
                title = {Text(
                    "Compose - Card Background Color",
                    color = Color.White)},
                backgroundColor = Color(0xFF58427C)) },
            content = {MainContent()},
            backgroundColor = Color(0xFFEDEAE0)
        )
    }


    @Composable
    fun MainContent(){
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(12.dp),
            verticalArrangement = Arrangement.SpaceEvenly,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(175.dp),
                backgroundColor = Color(0xFFFFBCD9),
                elevation = 4.dp,
                shape = RoundedCornerShape(24.dp),
            ) {
                Box(Modifier.padding(16.dp)) {
                    Text(
                        text = "Card Solid Background",
                        style = MaterialTheme.typography.h6
                    )
                }
            }

            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(175.dp),
                backgroundColor= Color.Transparent,
                elevation = 4.dp,
                shape = RoundedCornerShape(24.dp),
            ) {
                Box(
                    Modifier
                        .background(
                            Brush.radialGradient(
                                listOf(
                                    Color(0XFFFAD6A5),
                                    Color(0XFFFF5470),
                                    Color(0XFF7DF9FF)
                                )
                            )
                        )
                        .padding(12.dp)
                ) {
                    Text(
                        text = "Card Gradient Background",
                        style = MaterialTheme.typography.h6
                    )
                }
            }
        }
    }


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

Jetpack Compose: How to add padding to a Card

Introduction

In this article, we will explore how to implement a simple UI layout using Jetpack Compose in Android by focusing on how to manage padding inside a card. Jetpack Compose is Google's modern toolkit for building native UI, which simplifies UI development by using Kotlin-based declarative programming. Instead of building UI components through XML layouts, Compose allows developers to define UI components directly in Kotlin, which brings flexibility and ease of use.

In this particular example, we will look at how to create a Card component with proper padding, alignment, and visual structure. This is achieved through various composable functions, leveraging the powerful Jetpack Compose framework. Let's dive into the different sections of the code to understand how these UI elements are constructed.

Main Activity Setup

The main entry point for this app is the MainActivity class, which extends AppCompatActivity. The onCreate() method is overridden to set the content view using the setContent function, a key part of Jetpack Compose that replaces traditional XML layouts. This function calls the GetScaffold() composable, which is responsible for creating the primary structure of the app. The use of Jetpack Compose's declarative approach allows the UI to be defined entirely in Kotlin.

The GetScaffold() function utilizes a Scaffold composable, a layout component that provides a base structure for the app, including slots for a top bar, content area, and more. In this case, a TopAppBar is defined with a title and a specific background color, giving the app a clean and structured look. The background color of the whole scaffold is set to a light beige-like color, adding a warm aesthetic to the UI.

MainContent Function

The core of the UI resides in the MainContent() composable function, which is responsible for displaying the Card component. This function is wrapped in a Column, which arranges its children vertically. The Column is customized with modifiers such as fillMaxSize() and padding(12.dp), ensuring that it occupies the entire screen space and includes some padding around the edges.

The Card component itself is where the focus of this example lies. It is set to have a fixed height of 150.dp and fills the available width, creating a large rectangular card in the UI. Several important visual properties are applied to the card, including a soft pink background color, a slight elevation for depth, rounded corners with a radius of 12.dp, and a border stroke with a width of 1.dp. These details give the card a polished and well-defined appearance.

Padding in the Card

Inside the Card, a Box composable is used to hold the card's content. The Box is a layout component that allows stacking of elements, and in this case, it is wrapped with a Modifier.padding(16.dp) to add internal padding. This ensures that the content inside the card does not touch the edges, creating a more balanced and visually appealing layout. The Text composable within the Box displays a simple label, styled with MaterialTheme.typography.h6, which ensures the text adheres to the app’s overall design system.

Preview Function

The ComposablePreview() function is marked with the @Preview annotation, which is a handy feature in Jetpack Compose. It allows you to see a real-time preview of your composable functions directly in the IDE without having to run the app on an actual device or emulator. While this function is commented out in the example, uncommenting it would let you visually test the GetScaffold() layout within Android Studio's preview window.

Summary

This example demonstrates how to build a basic card layout in Jetpack Compose, focusing on using padding and alignment effectively to create a visually appealing UI. By utilizing composables like Card, Column, and Box, along with Modifier properties for padding, alignment, and size, this code achieves a clean and functional design. Jetpack Compose’s declarative approach allows developers to define UI elements directly in Kotlin, streamlining the process and reducing the need for XML layouts. This setup offers flexibility and ease of development, making it a preferred choice for modern Android UI design.


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.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp

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

        setContent {
            GetScaffold()
        }
    }


    @Composable
    fun GetScaffold(){
        Scaffold(
            topBar = {TopAppBar(
                title = {Text(
                    "Compose - Card Padding",
                    color = Color.White)},
                backgroundColor = Color(0xFF58427C)) },
            content = {MainContent()},
            backgroundColor = Color(0xFFEDEAE0)
        )
    }


    @Composable
    fun MainContent(){
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(12.dp),
            verticalArrangement = Arrangement.SpaceEvenly,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(150.dp),
                backgroundColor = Color(0xFFFFBCD9),
                elevation = 4.dp,
                shape = RoundedCornerShape(12.dp),
                border = BorderStroke(
                    width = 1.dp,
                    color = Color(0xFF9E1B32)
                )
            ) {
                Box(Modifier.padding(16.dp)) {
                    Text(
                        text = "Card Padding 16 DP",
                        style = MaterialTheme.typography.h6
                    )
                }
            }
        }
    }


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

Jetpack Compose: How to add a border to a Card

Introduction

Jetpack Compose, Google's modern toolkit for building native UI, provides a powerful and flexible way to design Android apps. One of the essential UI components is the Card, which offers an easy-to-use container for displaying content with visual appeal. Customizing the appearance of a Card is a common requirement, and one way to enhance its design is by adding a border. In this article, we will explore how to add different types of borders to a Card using Kotlin in Jetpack Compose. We will break down the code to show how to implement both a solid and gradient border to enhance the UI experience.

The ability to style components like cards with borders allows developers to create visually engaging and unique designs. This tutorial demonstrates how to add a solid color border and a gradient border, two commonly used techniques, to Card elements within a layout using Jetpack Compose.

Setting up the Scaffold

The main user interface is built within a Scaffold, which provides a structure with a top bar and content area. The Scaffold component is initialized in the onCreate() method by calling the GetScaffold() composable. In this example, the TopAppBar component is used to display a title at the top of the screen, giving the app a clean header. The background color of the top bar is set to a custom purple shade, while the background color for the Scaffold itself is set to a light beige tone, providing a contrast between the header and the content area.

The Scaffold composable serves as the container for the app’s content, allowing the placement of various UI elements. Here, it hosts the MainContent() composable, where the actual card elements are placed. This structure helps keep the code organized and modular.

The MainContent Composable

The MainContent() function is where the layout and the two Card components are defined. This function organizes the layout using a Column, which vertically arranges its child elements. The Column is styled to fill the available screen size and includes padding for spacing. To ensure the cards are evenly spaced, the Arrangement.SpaceEvenly property is applied, along with center alignment.

Each card is given a Modifier that sets its width, height, and elevation, providing a 3D shadow effect. The use of RoundedCornerShape rounds the card's corners, creating a softer appearance. By specifying different properties for each card, we achieve a varied visual design within the same layout.

Adding a Solid Border to the Card

The first card features a solid border. To add this, the border parameter of the Card composable is set to a BorderStroke. This stroke is defined with a specific width (2.dp) and a solid color (dark red). The solid border effectively outlines the card, making it visually distinct against the background and helping it stand out. Inside the card, a Box composable centers the text "Card Solid Border" within the available space.

This approach to adding a border is straightforward, using a single color and providing a clean, bold look.

Adding a Gradient Border to the Card

The second card introduces a gradient border, adding a dynamic and visually appealing effect. The BorderStroke for this card uses a Brush with a linearGradient to create a two-color gradient. The gradient transitions from a deep blue to a bright red, creating a smooth and modern border effect that catches the user's eye.

The gradient brush adds a more complex and visually interesting appearance compared to the solid border. Like the previous card, this card also includes a Box to center the text, which reads "Card Gradient Border." The use of gradient borders is ideal for more creative designs or when you want to add a more sophisticated flair to the UI.

Summary

In this tutorial, we explored how to add both solid and gradient borders to Card components in Jetpack Compose. By utilizing the BorderStroke and Brush features, we can easily enhance the visual appearance of cards, providing clear outlines and creative styling options. We also structured the app's UI using a Scaffold with a top bar and a column layout to arrange the cards evenly on the screen.

Whether you're aiming for a minimalistic look with a solid border or a more dynamic and colorful design with a gradient border, Jetpack Compose offers the tools to achieve these effects with ease. This flexibility allows developers to create polished and engaging UIs that meet various design requirements.


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.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp

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

        setContent {
            GetScaffold()
        }
    }


    @Composable
    fun GetScaffold(){
        Scaffold(
            topBar = {TopAppBar(
                title = {Text(
                    "Compose - Card Border",
                    color = Color.White)},
                backgroundColor = Color(0xFF58427C)) },
            content = {MainContent()},
            backgroundColor = Color(0xFFEDEAE0)
        )
    }


    @Composable
    fun MainContent(){
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(12.dp),
            verticalArrangement = Arrangement.SpaceEvenly,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(150.dp),
                backgroundColor = Color(0xFFFFA700),
                elevation = 4.dp,
                shape = RoundedCornerShape(12.dp),
                border = BorderStroke(
                    width = 2.dp,
                    color = Color(0xFF58111A)
                )
            ) {
                Box(Modifier.wrapContentSize(Alignment.Center)){
                    Text(
                        text = "Card Solid Border",
                        style = MaterialTheme.typography.h6
                    )
                }
            }

            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(150.dp),
                backgroundColor = Color(0xFFFFAA1D),
                elevation = 8.dp,
                shape = RoundedCornerShape(12.dp),
                border = BorderStroke(
                    width = 3.dp,
                    brush = Brush.linearGradient(
                        listOf(
                            Color(0xFF0047AB),
                            Color(0xFFFF3800)
                        )
                    )
                )
            ) {
                Box(Modifier.wrapContentSize(Alignment.Center)){
                    Text(
                        text = "Card Gradient Border",
                        style = MaterialTheme.typography.h6
                    )
                }
            }
        }
    }


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

Jetpack Compose: How to add shadow to a Card

Introduction

Jetpack Compose, Android’s modern toolkit for building native UI, allows developers to create beautiful, responsive applications with less code. One of the appealing features of Jetpack Compose is its simplicity in designing UI components such as cards, which are widely used to display information. A common requirement when using cards is to add shadow effects or elevation to enhance visual aesthetics, giving a more defined and interactive feel. In this guide, we’ll explore how to add shadow to a card component in Jetpack Compose, using simple steps to control elevation for better user experience.

This tutorial walks you through creating a basic layout with multiple cards in Android using Jetpack Compose. It covers how to control the elevation (which adds a shadow effect) and how to customize the card’s appearance with different shapes and background colors. Each card in the example has a different elevation value, showing how the shadow effect varies based on this property.

Scaffold and TopAppBar

The entry point of the application is the MainActivity, where Jetpack Compose’s setContent function is used to display the composable UI. The composable function GetScaffold() serves as the structure for the app’s layout. It uses the Scaffold composable to create a layout that follows Material Design principles, including a TopAppBar. The TopAppBar provides a consistent header across the app with a customizable title. In this example, the top bar is titled "Compose - Card Shadow" and is styled with a purple background and white text.

The Scaffold function also defines the background color of the app and sets the main content with a call to MainContent(), where the core card components are designed and laid out.

MainContent and Card Structure

The MainContent() function contains a Column composable that arranges the cards vertically. The Column is styled to fill the available screen space, with padding to add some spacing between the edges of the screen and the content. The cards are centered both vertically and horizontally, ensuring a visually balanced layout. Inside this column, three different cards are displayed, each having varying levels of elevation (shadow).

Each card is created using the Card composable. The cards are assigned a Modifier to adjust their size and layout properties, such as full-width and specific height settings. The cards also feature a distinct background color (a vibrant orange) and rounded corners. The shadow effect on each card is controlled by the elevation parameter, where values like 4.dp, 8.dp, and 12.dp are used to create different shadow intensities.

Shadow Effect with Elevation

The elevation parameter in Jetpack Compose controls the depth at which a card appears to float above the surface, which creates a shadow. This shadow effect is particularly useful for adding depth to the UI, making the elements more visually appealing and interactive. In this example, three cards are displayed, each with different elevations:

  • Card 1: Has an elevation of 4.dp, providing a subtle shadow effect.
  • Card 2: Elevation is set to 8.dp, making the shadow more pronounced.
  • Card 3: Features an elevation of 12.dp, where the shadow is strongest, making the card appear to be floating higher than the others.

This demonstrates how varying the elevation value can significantly affect the visual hierarchy of components.

Shapes and Customization

In addition to elevation, cards in Jetpack Compose can be customized with different shapes and sizes. The first two cards use a RoundedCornerShape with a 12.dp radius, giving them smooth, rounded edges that enhance the visual appeal. The third card, however, uses a CircleShape, creating a perfect circular card, which is also elevated at 12.dp. This highlights the flexibility of Jetpack Compose, where designers can not only control shadow effects but also shape the components to fit the desired design.

Summary

In summary, adding shadows to cards in Jetpack Compose is straightforward, thanks to the elevation property. By adjusting this value, you can create a range of shadow effects that help emphasize elements and guide user interaction. This example also demonstrates the power of composables in designing flexible, customizable UI components with minimal code. The ability to easily set shapes, colors, and elevations makes Jetpack Compose a versatile tool for building responsive, modern UIs.

This tutorial highlights how combining simplicity with customization allows developers to build visually rich applications. With a solid understanding of elevation and card design in Jetpack Compose, you can now experiment with more complex layouts and designs for your Android apps.


MainActivity.kt

package com.cfsuman.jetpackcompose

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp

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

        setContent {
            GetScaffold()
        }
    }


    @Composable
    fun GetScaffold(){
        Scaffold(
            topBar = {TopAppBar(
                title = {Text(
                    "Compose - Card Shadow",
                    color = Color.White)},
                backgroundColor = Color(0xFF58427C)) },
            content = {MainContent()},
            backgroundColor = Color(0xFFEDEAE0)
        )
    }


    @Composable
    fun MainContent(){
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(12.dp),
            verticalArrangement = Arrangement.SpaceEvenly,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(150.dp),
                backgroundColor = Color(0xFFFFAA1D),
                elevation = 4.dp,
                shape = RoundedCornerShape(12.dp),
            ) {
                Box(Modifier.wrapContentSize(Alignment.Center)){
                    Text(
                        text = "Card Elevation/Shadow 4 DP",
                        style = MaterialTheme.typography.h6
                    )
                }
            }

            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(150.dp),
                backgroundColor = Color(0xFFFFAA1D),
                elevation = 8.dp,
                shape = RoundedCornerShape(12.dp),
            ) {
                Box(Modifier.wrapContentSize(Alignment.Center)){
                    Text(
                        text = "Card Elevation/Shadow 8 DP",
                        style = MaterialTheme.typography.h6
                    )
                }
            }

            Card(
                modifier = Modifier.size(200.dp),
                backgroundColor = Color(0xFFFFAA1D),
                elevation = 12.dp,
                shape = CircleShape,
            ) {
                Box(Modifier.wrapContentSize(Alignment.Center)){
                    Text(
                        text = "Elevation 12 DP",
                        style = MaterialTheme.typography.h6
                    )
                }
            }
        }
    }


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

Jetpack Compose: Card corner radius

Introduction

Jetpack Compose, the modern UI toolkit from Android, provides a simple and powerful way to design user interfaces using a declarative approach. One of the key features of Compose is its flexibility when it comes to customizing UI components, such as applying different shapes, including corner radii, to visual elements like Cards. In this Kotlin example, we explore how to use Jetpack Compose to create cards with varying corner radius effects, demonstrating the power and ease of UI customization.

This description breaks down the code of an Android activity that showcases the use of Compose Card components with different shapes, including rounded corners and circular shapes. The use of Scaffold to structure the layout and the way Card elements are styled with custom radii will be highlighted in this detailed walkthrough.

Main Structure

The core of this example lies in MainActivity, which inherits from AppCompatActivity. Inside the onCreate() method, the setContent function is called to define the layout of the activity using Jetpack Compose. The layout is composed through a call to GetScaffold(), which sets up a top bar and the main content of the activity, following a common UI structure for Android apps.

The Scaffold composable provides a framework for arranging the overall screen layout. In this example, it is used to define a TopAppBar with a title and a main content area. The top bar is simple, displaying the title "Compose - Card Corner Radius" with a specific background color. The rest of the screen's content is handled by the MainContent() composable, which is where the different card designs are implemented.

Card Customizations

Within MainContent(), three Card components are defined, each with a unique shape to demonstrate different corner-radius effects. The Column composable is used to arrange these cards vertically, with space evenly distributed between them. Each card is wrapped in a Box, which helps in centering the text inside.

The first card uses RoundedCornerShape with a corner radius of 12 dp. This gives the card evenly rounded corners on all sides. The card has a red background color and is styled with an elevation of 4 dp, which adds a subtle shadow effect. The text "Card Corner Radius 12 DP" is displayed at the center of the card.

The second card is similar in structure but applies a different shape. It uses RoundedCornerShape with a radius of 20 dp only at the top-end corner. This customization creates a card with one distinctively rounded corner while the other corners remain sharp. The card is given a blue background, making it visually distinct from the others.

The third card takes a different approach by applying a CircleShape, creating a fully circular card. The circular card has a fixed size of 200 dp for both width and height. It uses a yellow-orange background and displays the text "Circular Card" in its center. This demonstrates how easily Compose allows for non-rectangular shapes like circles to be integrated into the UI.

Preview and Testing

The example code includes a ComposablePreview() function, which is annotated with @Preview. This function is typically used in Jetpack Compose to provide a preview of the UI within Android Studio's design tools. Although the GetScaffold() function is commented out in the preview, it is here as a placeholder, allowing developers to easily preview the UI if they choose to enable it.

Summary

In summary, this Kotlin example demonstrates the flexibility of Jetpack Compose in designing UI components with custom shapes and corner radii. By utilizing composables like Card, Column, and Box, developers can easily create cards with rounded corners or circular shapes, giving them the freedom to design visually appealing interfaces. The use of Scaffold helps in structuring the layout with a top bar and main content area, while the customization of corner radii highlights how Compose makes UI design both simple and expressive.


MainActivity.kt

package com.cfsuman.jetpackcompose

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp

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

        setContent {
            GetScaffold()
        }
    }


    @Composable
    fun GetScaffold(){
        Scaffold(
            topBar = {TopAppBar(
                title = {Text(
                    "Compose - Card Corner Radius",
                    color = Color.White)},
                backgroundColor = Color(0xFF58427C)) },
            content = {MainContent()},
            backgroundColor = Color(0xFFEDEAE0)
        )
    }


    @Composable
    fun MainContent(){
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(12.dp),
            verticalArrangement = Arrangement.SpaceEvenly,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(150.dp),
                backgroundColor = Color(0xFFE97451),
                elevation = 4.dp,
                shape = RoundedCornerShape(12.dp),
            ) {
                Box(Modifier.wrapContentSize(Alignment.Center)){
                    Text(
                        text = "Card Corner Radius 12 DP",
                        style = MaterialTheme.typography.h6
                    )
                }
            }

            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(150.dp),
                backgroundColor = Color(0xFF1F75FE),
                elevation = 4.dp,
                shape = RoundedCornerShape(topEnd = 20.dp),
            ) {
                Box(Modifier.wrapContentSize(Alignment.Center)){
                    Text(
                        text = "Top End Only 20 DP",
                        style = MaterialTheme.typography.h6
                    )
                }
            }

            Card(
                modifier = Modifier.size(200.dp),
                backgroundColor = Color(0xFFFFAA1D),
                elevation = 4.dp,
                shape = CircleShape,
            ) {
                Box(Modifier.wrapContentSize(Alignment.Center)){
                    Text(
                        text = "Circular Card",
                        style = MaterialTheme.typography.h6
                    )
                }
            }
        }
    }


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

Jetpack Compose: How to center content within a Card

Introduction

In modern Android development, Jetpack Compose is transforming how we build UI elements, providing a declarative way to design layouts. Among the many components available in Jetpack Compose, the Card is a useful element that helps organize content with elevation, background colors, and rounded corners. This example showcases how to place content in the center of a Card component using Jetpack Compose in Kotlin. Understanding the use of Card and its layout behavior is essential for creating clean and visually appealing interfaces.

This article describes a simple Android project that places text content in the center of a Card component. It walks through the different composable functions involved and explains how Jetpack Compose layouts, such as Scaffold, Column, Card, and Box, can be combined to achieve the desired UI behavior.

Project Breakdown

The project begins with an AppCompatActivity class where the main composable function is set up. Inside the onCreate method, the setContent function is called, which initializes the Composable UI by invoking the GetScaffold composable function. Scaffold is a powerful layout structure in Jetpack Compose that provides a standard layout with pre-configured components such as a top bar, content area, and background color. In this case, the Scaffold function sets a top bar with a title and a background color, as well as the main content area.

Within the GetScaffold function, the TopAppBar displays a title at the top of the screen. This title is placed inside a Text composable, and a custom color is applied to the text and the app bar background. The Scaffold also specifies a background color for the entire screen, providing a consistent look and feel.

The core functionality of centering content inside a Card happens in the MainContent composable function. This function uses a Column layout with padding to structure the content vertically. Inside the column, a Card composable is added. The Card is given specific dimensions using the fillMaxWidth modifier to ensure it spans the entire screen width, and the height modifier sets its height to 250 dp. The Card is styled with a green background color, a slight elevation, and rounded corners using the RoundedCornerShape function.

To center the content inside the Card, a Box composable is used. Box is a versatile layout that allows overlapping content and provides an easy way to position child components. The wrapContentSize(Alignment.Center) modifier is applied to the Box, ensuring that the text content inside the card is centered both horizontally and vertically. The text itself is displayed using a Text composable with a material theme typography style to give it a consistent, polished look.

Conclusion

This simple Jetpack Compose example illustrates how to center content within a Card using a combination of Box and alignment modifiers. By leveraging Scaffold for layout structure, Card for content presentation, and Box for flexible alignment, developers can efficiently create well-structured and visually appealing UI components. The usage of Jetpack Compose greatly simplifies UI development, making it more intuitive compared to the traditional view-based system in Android.

Overall, this approach demonstrates the declarative nature of Jetpack Compose and how easily developers can create and manipulate layouts to achieve a desired design. Centering content within a Card is just one example of the flexibility and power of Compose in modern Android applications.


MainActivity.kt

package com.cfsuman.jetpackcompose

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp

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

        setContent {
            GetScaffold()
        }
    }


    @Composable
    fun GetScaffold(){
        Scaffold(
            topBar = {TopAppBar(
                title = {Text(
                    "Compose - Card Center",
                    color = Color.White)},
                backgroundColor = Color(0xFF58427C)) },
            content = {MainContent()},
            backgroundColor = Color(0xFFEDEAE0)
        )
    }


    @Composable
    fun MainContent(){
        Column(modifier = Modifier.padding(12.dp)) {
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(250.dp),
                backgroundColor = Color(0xFF8DB600),
                elevation = 4.dp,
                shape = RoundedCornerShape(12.dp),
            ) {
                Box(Modifier.wrapContentSize(Alignment.Center)){
                    Text(
                        text = "Card Center",
                        style = MaterialTheme.typography.h5
                    )
                }
            }
        }
    }


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

Jetpack Compose: Box gravity example

Introduction

This example demonstrates the use of Jetpack Compose’s Box composable in an Android app to explore alignment and gravity within a UI. The Kotlin-based example showcases how to structure a simple user interface, positioning elements within a Box using different alignment settings. The sample app is designed to help Android developers understand how Box works in Jetpack Compose and how to apply various layout and alignment options effectively. It uses simple components, including a Scaffold, to wrap the layout and provide a consistent structure with a top bar.

Structure and Setup

The starting point of this project is the MainActivity, which extends AppCompatActivity. Upon creation of the activity, the setContent function is called to initiate the composable functions. The core layout is defined by the GetScaffold() composable, which is responsible for organizing the entire screen content. Within this scaffold, there is a TopAppBar that gives the app a standard navigation bar at the top. The rest of the screen's content is handled by the MainContent() function, where the layout is designed using a Column containing multiple Box elements.

The Scaffold and App Bar

The Scaffold composable is used to manage the overall layout of the app, providing areas for the top bar, bottom bar, floating action button, and content. In this example, the top bar is created using the TopAppBar composable, which contains a Text widget that displays the title "Compose - Box Gravity" with a custom background color. This ensures that the UI has a familiar app structure while focusing on the content aligned within the main area.

Layout with Column and Box

The core of the user interface is managed inside the MainContent() composable, which is responsible for arranging the Box elements vertically using a Column. The Column is designed to take up the full screen space (fillMaxSize()) and ensures that the Box elements are evenly spaced using the Arrangement.SpaceEvenly parameter. The alignment of the content within each Box is a key feature of this example, showcasing how Jetpack Compose manages gravity or alignment through the contentAlignment property.

Understanding Box Alignment

The Box composable is a powerful container that allows for precise control over the positioning of its content. In this example, three different Box components demonstrate various alignments:

  • Center Alignment: The first Box centers its text content both vertically and horizontally. This is achieved by setting contentAlignment = Alignment.Center, which is useful for creating balanced layouts where content needs to be symmetrically aligned.

  • Center Vertically, Start Horizontally: The second Box demonstrates vertical centering combined with left alignment. The contentAlignment = Alignment.CenterStart parameter ensures the text is centered vertically but aligned to the start of the container horizontally, providing a clear example of how to manage mixed alignments.

  • Top Center Alignment: In the third Box, the content is aligned at the top center of the container. This is specified using contentAlignment = Alignment.TopCenter, allowing for a different layout where the text begins at the top but remains centered horizontally.

Each Box is styled with distinct padding, background colors, and rounded corners, making it visually easy to distinguish the different alignment properties.

Previewing the Layout

A ComposablePreview() function is included to allow easy previewing of the UI in Android Studio's preview window. Although it’s commented out in this example, this function is an essential part of the Compose development workflow, enabling developers to view and adjust layouts without needing to run the app on a device or emulator.

Summary

In summary, this example serves as an excellent introduction to Jetpack Compose’s Box composable and how gravity and alignment can be managed within layouts. By utilizing different Alignment properties, developers can control the positioning of elements inside a Box and create flexible UI designs. The combination of Scaffold, Column, and Box in this example demonstrates a clear and modular approach to UI development in Jetpack Compose, offering both simplicity and versatility. Understanding these basics is critical for building complex and dynamic user interfaces in modern Android applications.


MainActivity.kt

package com.cfsuman.jetpackcompose

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp

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

        setContent {
            GetScaffold()
        }
    }


    @Composable
    fun GetScaffold(){
        Scaffold(
            topBar = {TopAppBar(
                title = {Text(
                    "Compose - Box Gravity",
                    color = Color.White)},
                backgroundColor = Color(0xFF58427C)) },
            content = {MainContent()},
            backgroundColor = Color(0xFFEDEAE0)
        )
    }


    @Composable
    fun MainContent(){
        Column(
            modifier = Modifier
                .fillMaxSize(),
            verticalArrangement = Arrangement.SpaceEvenly,
            horizontalAlignment = Alignment.CenterHorizontally
        ){
            Box(
                Modifier
                    .padding(12.dp)
                    .fillMaxWidth()
                    .height(150.dp)
                    .clip(RoundedCornerShape(12.dp))
                    .background(Color(0xFFB2FFFF))
                    .padding(12.dp),
                contentAlignment = Alignment.Center
            ){
                Text(
                    text = "Gravity Center",
                    style = MaterialTheme.typography.caption
                )
            }

            Box(
                Modifier
                    .padding(12.dp)
                    .fillMaxWidth()
                    .height(150.dp)
                    .clip(RoundedCornerShape(12.dp))
                    .background(Color(0xFFB2EC5D))
                    .padding(12.dp),
                contentAlignment = Alignment.CenterStart
            ){
                Text(
                    text = "Gravity Center Vertically",
                    style = MaterialTheme.typography.caption
                )
            }

            Box(
                Modifier
                    .padding(12.dp)
                    .fillMaxWidth()
                    .height(150.dp)
                    .clip(RoundedCornerShape(12.dp))
                    .background(Color(0xFFD6CADD))
                    .padding(12.dp),
                contentAlignment = Alignment.TopCenter
            ){
                Text(
                    text = "Gravity Center Horizontally",
                    style = MaterialTheme.typography.caption
                )
            }
        }
    }


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

jetpack compose - Box content alignment

Compose Box Content Alignment
The Box is a layout widget of the android jetpack compose library. The Box layout size itself fits the content. When a Box layout size is bigger than the content size, then we have to align the content. Such as a Box layout may be filled the screen size, in this situation we need to show the content widget at the specified position of the Box layout.

The following jetpack compose tutorial will demonstrate to us how we can align Box content in an android application. The Box widget constructor has an argument name ‘contentAlignment’ whose data type is ‘Alignment’. So, using this argument we can set the Box content alignment.

Alignment is an interface to calculate the position of a sized box inside an available space. The ‘Alignment’ is often used to define the alignment of a layout inside a parent layout.

The default value of this ‘contentAlignment’ argument is ‘Alignment.TopStart’. There are many available values for the ‘contentAlignment’ argument such as Alignment.Center, Alignment.TopEnd, Alignment.BottomStart, Alignment.CenterStart, etc. Those names are self-describing. So, if we want to put an element at the exact center of the Box layout, then we can simply pass the ‘contentAlignment’ argument value to ‘Alignment.Center’.

This jetpack compose tutorial code is written in an android studio IDE. Copy the code and run it on an emulator device or a real device to test how we define the Box layout content alignment. We also displayed a screenshot of this tutorial’s emulator screen at the bottom of this tutorial.
MainActivity.kt

package com.cfsuman.jetpackcompose

import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp

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

        setContent {
            GetScaffold()
        }
    }


    @SuppressLint("UnusedMaterialScaffoldPaddingParameter")
    @Composable
    fun GetScaffold(){
        Scaffold(
            topBar = {TopAppBar(
                title = {Text(
                    "Compose - Box Alignment",
                    color = Color.White)},
                backgroundColor = Color(0xFF58427C)) },
            content = {MainContent()},
            backgroundColor = Color(0xFFEDEAE0)
        )
    }


    @Composable
    fun MainContent(){
        Column(
            modifier = Modifier
                .fillMaxSize(),
            verticalArrangement = Arrangement.SpaceEvenly,
            horizontalAlignment = Alignment.CenterHorizontally
        ){
            Box(
                Modifier
                    .padding(12.dp)
                    .fillMaxWidth()
                    .height(150.dp)
                    .clip(RoundedCornerShape(12.dp))
                    .background(Color(0xFFEEDC82))
                    .padding(12.dp),
                contentAlignment = Alignment.Center
            ){
                Text(text = "Center Alignment")
            }

            Box(
                Modifier
                    .padding(12.dp)
                    .fillMaxWidth()
                    .height(150.dp)
                    .clip(RoundedCornerShape(12.dp))
                    .background(Color(0xFFA8E4A0))
                    .padding(12.dp),
                contentAlignment = Alignment.BottomStart
            ){
                Text(text = "Alignment Bottom Start")
            }

            Box(
                Modifier
                    .padding(12.dp)
                    .fillMaxWidth()
                    .height(150.dp)
                    .clip(RoundedCornerShape(12.dp))
                    .background(Color(0xFFE9D66B))
                    .padding(12.dp),
                contentAlignment = Alignment.TopEnd
            ){
                Text(text = "Alignment Top End")
            }
        }
    }


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

Jetpack Compose: Box rounded corners shape

Introduction

Jetpack Compose is a modern toolkit for building native UI in Android, simplifying and accelerating UI development by using Kotlin code. One of its key strengths is the flexibility it provides in designing user interfaces, including easily customizing shapes, layouts, and components. In this example, we focus on using Box components in Jetpack Compose to create UI elements with rounded corners and circular shapes, illustrating how to handle custom shapes in your UI.

In this article, we will break down an example Android app that demonstrates how to implement different box shapes such as boxes with rounded corners and circular shapes. The components are composed using Jetpack Compose’s powerful layout system, and the app includes a top app bar, background colors, and neatly arranged elements. We will walk through the core components and techniques used to achieve these shapes.

Scaffold Layout and AppBar Setup

The app's UI is built inside a Scaffold composable, which provides a structure for the main UI elements like the top app bar and content layout. The top app bar is created using TopAppBar, where the title is set to "Compose - Box Rounded Corners" with a background color for distinction. The Scaffold composable serves as the container for the rest of the content, and it uses the MainContent composable to display the core elements of the app. This structure ensures that the app maintains a consistent layout with a clear hierarchy of UI components.

The overall background of the app is set to a light color, which helps highlight the various colored Box components used later in the MainContent composable.

MainContent Layout

The MainContent composable is where the core visual elements of the app are defined. The elements are arranged in a column using the Column composable, which enables vertical stacking of child components. Within the Column, the verticalArrangement and horizontalAlignment parameters are used to evenly space out the child elements and center them horizontally.

Each child within the Column is a Box composable with different modifications applied to showcase rounded and circular shapes. These Box components act as containers for content, and they are customized using various layout modifiers to control their appearance and positioning.

Creating Boxes with Rounded Corners

The first Box in the MainContent composable demonstrates how to create a rectangle with rounded corners. The clip modifier is used with the RoundedCornerShape to round the corners of the Box to 12dp. The background color of the box is set to a light blue, and the text inside the box ("Rounded Corners 12 DP") is centered using the contentAlignment parameter.

The second Box builds on this by demonstrating how to round only specific corners. In this case, the top-right corner is rounded to 20dp using the RoundedCornerShape(topEnd = 20.dp). This shows the flexibility Jetpack Compose offers when customizing the shape of a UI component.

Circular Box Shape

The third Box demonstrates how to create a circular shape using the CircleShape composable. By setting the width and height of the Box to 150dp and applying the clip(CircleShape) modifier, the box is transformed into a perfect circle. The background color of this circular box is set to a light orange, and like the previous boxes, text is placed in the center for clarity.

The use of CircleShape in this context simplifies the creation of circular UI elements, which is often useful for avatars or icons in a modern Android app.

Conclusion

This example showcases how easy it is to create rounded and circular shapes in Jetpack Compose using simple layout modifiers and built-in shape options like RoundedCornerShape and CircleShape. The flexibility provided by Jetpack Compose’s declarative UI framework allows developers to quickly experiment with different shapes, layouts, and designs while writing concise and readable code.

By understanding the core concepts used in this example, such as the Scaffold, Box, and clip modifiers, developers can create sophisticated and visually appealing UIs with minimal effort. Jetpack Compose continues to push the boundaries of Android UI development, making it an essential tool for modern Android applications.


MainActivity.kt

package com.cfsuman.jetpackcompose

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp

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

        setContent {
            GetScaffold()
        }
    }


    @Composable
    fun GetScaffold(){
        Scaffold(
            topBar = {TopAppBar(
                title = {Text(
                    "Compose - Box Rounded Corners",
                    color = Color.White)},
                backgroundColor = Color(0xFF58427C)) },
            content = {MainContent()},
            backgroundColor = Color(0xFFEDEAE0)
        )
    }


    @Composable
    fun MainContent(){
        Column(
            modifier = Modifier
                .fillMaxSize(),
            verticalArrangement = Arrangement.SpaceEvenly,
            horizontalAlignment = Alignment.CenterHorizontally
        ){
            Box(
                Modifier
                    .padding(12.dp)
                    .fillMaxWidth()
                    .height(150.dp)
                    .clip(RoundedCornerShape(12.dp))
                    .background(Color(0xFFB9D9EB)),
                contentAlignment = Alignment.Center
            ){
                Text(text = "Rounded Corners 12 DP")
            }

            Box(
                Modifier
                    .padding(12.dp)
                    .fillMaxWidth()
                    .height(150.dp)
                    .clip(RoundedCornerShape(topEnd = 20.dp))
                    .background(Color(0xFFC2B280)),
                contentAlignment = Alignment.Center
            ){
                Text(text = "Rounded Corners Top End Only 20 DP")
            }

            Box(
                Modifier
                    .padding(12.dp)
                    .width(150.dp)
                    .height(150.dp)
                    .clip(CircleShape)
                    .background(Color(0xFFE5AA70)),
                contentAlignment = Alignment.Center
            ){
                Text(text = "Circle Shape")
            }
        }
    }


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