How to create a Simple Card in Android Jetpack Compose

By Mohammed Rashid •  November 16th, 2022 • 

For mobile apps or websites, the cards are beautiful UI components that can be used in any project. In this blog post, let’s learn how to create a card in Android Jetpack Compose.

The card is a container with elevation and shadows. We can customize it by adding borders and border-radius. See the code snippet given below.

package com.example.myapplication

import android.os.Bundle
import androidx.activity.ComponentActivity
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.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.myapplication.ui.theme.MyApplicationTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyApplicationTheme {
                Surface(
                    color = MaterialTheme.colors.background
                ) {
                    Example()
                }
            }
        }
    }
}

@Composable
fun Example() {
    Card(modifier = Modifier
        .width(300.dp)
        .height(100.dp).padding(20.dp),
        elevation = 10.dp,
        backgroundColor = Color.White,
        border = BorderStroke(width = 2.dp, color = Color.Blue),
        shape = RoundedCornerShape(10.dp)

    ) {
        Text(text = "This is a Card", modifier = Modifier.padding(20.dp))
    }
}


@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    MyApplicationTheme {
        Example()
    }
}

Following is the output.

That’s how you add cards in Jetpack Compose.

Mohammed Rashid

Keep Reading