Jetpack Compose Button (with Examples)

Jetpack Compose Button

In this article, we will learn how to implement a button in Jetpack Compose with the help of examples.

Prerequisites:

This article talks about the Material 2 Button. If you want the Material 3 version, follow this link.

What is Button in Android?

A button is a UI element that a user can interact with by clicking or tapping it. It typically contains a text label that says what happens when we tap on it.

Example:

Button Example
A sign up button

If you want to follow along with this article, create a MyUI() composable in the MainActivity, and call it from the onCreate() method.

// add the following imports
import android.os.Bundle
import android.widget.Toast
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.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            YourProjectNameTheme(darkTheme = false) {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    Column(
                        modifier = Modifier.fillMaxSize(),
                        verticalArrangement = Arrangement.Center,
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        MyUI()
                    }
                }
            }
        }
    }
}

@Composable
fun MyUI() {

}

We will write our code in MyUI().

Jetpack Compose provides Button() API:

@Composable
fun Button(
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
    enabled: Boolean = true,
    interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
    elevation: ButtonElevation? = ButtonDefaults.elevation(),
    shape: Shape = MaterialTheme.shapes.small,
    border: BorderStroke? = null,
    colors: ButtonColors = ButtonDefaults.buttonColors(),
    contentPadding: PaddingValues = ButtonDefaults.ContentPadding,
    content: @Composable RowScope.() -> Unit
)

Let’s understand it with examples.

Simple Button Example:

For a basic button, the onClick parameter is mandatory. It is a lambda that gets called when we tap on the button.

@Composable
fun MyUI() {
    val contextForToast = LocalContext.current.applicationContext

    Button(
        onClick = {
            // click event
            Toast.makeText(contextForToast, "Clicked!", Toast.LENGTH_SHORT).show()
        }
    ) {
        // add button content here.
        // all the items are added in a row.
        Text(text = "Click Me")
    }
}

Output:

Simple Button Example

The code is simple. In the onClick block, we are showing a toast message. In the content, we have added a Text composable. The content block is a row scope. So, if you add multiple items, they will be arranged in a Row.

Button Text Color and Padding:

We can customize the button text using the Text() composable.

@Composable
fun MyUI() {
    val contextForToast = LocalContext.current.applicationContext

    Button(
        onClick = {
            Toast.makeText(contextForToast, "Clicked!", Toast.LENGTH_SHORT).show()
        }
    ) {
        Text(
            modifier = Modifier.padding(all = 12.dp),
            text = "Click Me",
            color = Color.Black
        )
    }
}

Output:

Button Text Color and Padding

Button with Icon and Text:

To display text with an icon, add Icon() and Text() composables in the content block. If you want to set a gap between them, use Spacer.

@Composable
fun MyUI() {
    val contextForToast = LocalContext.current.applicationContext

    Button(
        onClick = {
            // click event
            Toast.makeText(contextForToast, "Clicked!", Toast.LENGTH_SHORT).show()
        }
    ) {
        // add button content here.
        // all the items are added in a row
        Icon(imageVector = Icons.Default.Add, contentDescription = "Add icon")
        Spacer(modifier = Modifier.width(width = 8.dp))
        Text(text = "ADD ME")
    }
}

Output:

Button with Icon and text

For the Add icon, you may need to include material icon dependency.

Button Shape:

We can customize the button shape using the shape parameter. Call the RoundedCornerShape() method and pass the desired corner size.

@Composable
fun MyUI() {
    val contextForToast = LocalContext.current.applicationContext

    Button(
        onClick = {
            Toast.makeText(contextForToast, "Clicked!", Toast.LENGTH_SHORT).show()
        },
        shape = RoundedCornerShape(size = 20.dp)
    ) {
        Text(text = "Click Me")
    }
}

Output:

Button Shape

Button Background Color:

The colors parameter helps us to change the background color. Call the buttonColors() method and pass the colors you want.

public final fun buttonColors(
    backgroundColor: Color,
    contentColor: Color,
    disabledBackgroundColor: Color,
    disabledContentColor: Color
): ButtonColors

Related: Colors in Jetpack Compose

Let’s set green as the background color:

@Composable
fun MyUI() {
    val contextForToast = LocalContext.current.applicationContext

    Button(
        onClick = {
            Toast.makeText(contextForToast, "Clicked!", Toast.LENGTH_SHORT).show()
        },
        colors = ButtonDefaults.buttonColors(
            backgroundColor = Color.Green
        )
    ) {
        Text(text = "Click Me")
    }
}

Output:

Button Background Color

Button Elevation and Shadow:

We use the elevation() method to customize the shadow below the button. We can set the shadow at different states.

public final fun elevation(
    defaultElevation: Dp,
    pressedElevation: Dp,
    disabledElevation: Dp,
    hoveredElevation: Dp,
    focusedElevation: Dp
): ButtonElevation

Let’s set 20.dp as the default elevation.

@Composable
fun MyUI() {
    val contextForToast = LocalContext.current.applicationContext

    Button(
        onClick = {
            Toast.makeText(contextForToast, "Clicked!", Toast.LENGTH_SHORT).show()
        },
       elevation = ButtonDefaults.elevation(
           defaultElevation = 20.dp
       )
    ) {
        Text(text = "Click Me")
    }
}

Output:

Button elevation and shadow

Note: If you want to remove the elevation, pass 0.dp.

Button Border:

We use the border parameter to add the border.

@Composable
fun MyUI() {
    val contextForToast = LocalContext.current.applicationContext

    Button(
        onClick = {
            Toast.makeText(contextForToast, "Clicked!", Toast.LENGTH_SHORT).show()
        },
        border = BorderStroke(width = 2.dp, color = Color.Magenta)
    ) {
        Text(text = "Click Me")
    }
}

Output:

Button Border

Button Size:

The Modifier‘s methods like width(), height(), fillMaxWidth(), etc. can be used to change the button size.

@Composable
fun MyUI() {
    val contextForToast = LocalContext.current.applicationContext

    Button(
        modifier = Modifier
            .width(width = 120.dp)
            .height(height = 64.dp),
        onClick = {
            Toast.makeText(contextForToast, "Clicked!", Toast.LENGTH_SHORT).show()
        }
    ) {
        Text(text = "Click Me")
    }
}

Output:

Button size

How to Disable the Button?

To disable the button, pass false to the enabled parameter. Once disabled, the button will not be clickable.

@Composable
fun MyUI() {

    var enabled by remember {
        mutableStateOf(true)
    }

    Button(
        onClick = {
            enabled = false
        },
        enabled = enabled
    ) {
        Text(text = if (enabled) "Disable Me!" else "I am Disabled!")
    }
}

Output:

Disable button

How to Create a Custom Button in Jetpack Compose?

The default Button() API follows the material guidelines. As a result, we cannot not fully customize it according to our requirements. But, we can use APIs like Box() and Surface() to create a complete custom button.

Example:

Corner Sizes

I have made the above ones using the Box() API. If you like it, take a look at all the custom buttons.

Button APIs in Jetpack Compose:

There are five other button composables:

  1. OutlinedButton
  2. TextButton
  3. IconButton
  4. IconToggleButton
  5. FloatingActionButton

This is all about the Button() composable in Jetpack Compose. I hope you have learned something new. If you have any doubts, comment below.

Related Articles:

Resources:

2 thoughts on “Jetpack Compose Button (with Examples)”

  1. Hi, Thanks for sharing. I am having a hard time to get the Button hoveredElevation to work. I am using Material3. There don’t seems to have any effect when my mouse hover over the button. Thanks in advance.
    My code:
    @Composable
    fun ButtonSample() {
    var enabled by remember { mutableStateOf(true) }

    Button(
    onClick = { enabled = !enabled },
    elevation = ButtonDefaults.buttonElevation(
    defaultElevation = 50.dp,
    pressedElevation = 0.dp,
    disabledElevation = 0.dp,
    hoveredElevation = 0.dp,
    ),
    ) { Text(if (enabled) “Button” else “Disabled”) }
    }

    Reply

Leave a Comment