How to add Elevation to Button in Android Jetpack Compose

By Mohammed Rashid •  September 4th, 2022 • 

Elevation in Material Design gives appropriate shadows for your UI element. In this Jetpack Compose tutorial, let’s learn how to add elevation to a button in Android.

Button composable allows you to add a button and its elevation parameter helps you to add elevation. See the code snippet given below.

@Composable
fun ElevatedButton() {
    Column {
        Button(onClick = { /*TODO*/ }, elevation =  ButtonDefaults.elevation(
            defaultElevation = 20.dp,
            pressedElevation = 15.dp,
            disabledElevation = 0.dp,
            hoveredElevation = 15.dp,
            focusedElevation = 10.dp
        )) {
            Text("Button with Elevation")
        }
    }
}

You can customize elevation for different states of the button. The complete code is given below.

package com.example.example
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.example.ui.theme.ExampleTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            ExampleTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    ElevatedButton()
                }
            }
        }
    }
}

@Preview(showBackground = true)
@Composable
fun ElevatedButton() {
    Column {
        Button(onClick = { /*TODO*/ }, elevation =  ButtonDefaults.elevation(
            defaultElevation = 20.dp,
            pressedElevation = 15.dp,
            disabledElevation = 0.dp,
            hoveredElevation = 15.dp,
            focusedElevation = 10.dp
        )) {
            Text("Button with Elevation")
        }
    }
}


@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    ExampleTheme {
        ElevatedButton()
    }
}

That’s how you add elevation or shadows to the button in Jetpack Compose.

Mohammed Rashid

Keep Reading