The Button
in Android Jetpack Compose is a composable function that allows you to create clickable buttons with different styles and actions. It's essential for building interactive user interfaces in Android apps.
@Composable
fun BasicButtonExample() {
Button(onClick = { /* Do something */ }) {
Text("Click Me")
}
}
This code creates a basic button with the text "Click Me". When clicked, it performs the action defined in the onClick
lambda.
@Composable
fun StyledButtonExample() {
Button(
onClick = { /* Do something */ },
colors = ButtonDefaults.buttonColors(backgroundColor = Color.Blue)
) {
Text("Styled Button", color = Color.White)
}
}
This code creates a styled button with a blue background and white text.
@Composable
fun IconButtonExample() {
Button(onClick = { /* Do something */ }) {
Icon(Icons.Default.Favorite, contentDescription = null)
Spacer(modifier = Modifier.size(ButtonDefaults.IconSpacing))
Text("Like")
}
}
This code creates a button with an icon (a heart) and text next to it.
@Composable
fun ShapedButtonExample() {
Button(
onClick = { /* Do something */ },
shape = RoundedCornerShape(12.dp)
) {
Text("Rounded Button")
}
}
This code creates a button with rounded corners.
@Composable
fun ElevatedButtonExample() {
Button(
onClick = { /* Do something */ },
elevation = ButtonDefaults.elevation(defaultElevation = 8.dp)
) {
Text("Elevated Button")
}
}
This code creates a button with a custom elevation of 8.dp, giving it a raised appearance.
The Button in Android Jetpack Compose is a versatile and powerful tool for creating interactive elements in your app's user interface. Understanding how to customize and use buttons effectively can enhance the usability and aesthetics of your Android applications.