Android Jetpack Compose – Set elevation for Card
In this tutorial, we shall learn how to set a specific elevation for a Card composable in Android Jetpack Compose, using elevation
property.
The following is an example for a Card with an elevation of 10.dp
.
The sample code snippet to set elevation for a Card composable is given below.
Card(
elevation = CardDefaults.cardElevation(
defaultElevation = 10.dp
),
)
Now, we shall take an example Android application, that displays a Card composable with a specific elevation of 10.dp
. You can change this value to suit your requirements.
MainActivity.kt
package com.example.myapplication
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
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 {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.fillMaxSize()
.padding(20.dp),
) {
CardExample()
}
}
}
}
}
@Composable
fun CardExample() {
Card(
modifier = Modifier
.padding(16.dp)
.fillMaxWidth(),
elevation = CardDefaults.cardElevation(
defaultElevation = 10.dp
),
) {
Column(
modifier = Modifier
.padding(16.dp)
.fillMaxWidth()
) {
Text(
text = "Card with elevation of 10.dp",
color = MaterialTheme.colorScheme.primary
)
Spacer(modifier = Modifier.height(8.dp))
Text(
text = "This is some sample text inside the card. You can add more content here.",
color = MaterialTheme.colorScheme.onSurface
)
}
}
}
Screenshot
Summary
In this tutorial, we have seen how to set a specific elevation for a card using elevation
property, using an example Android Application.