Here’s a simple example of using a Button in Jetpack Compose:
Basic Button Example
@Composable
fun SimpleButtonExample() {
var clickCount by remember { mutableStateOf(0) }
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Button(
onClick = { clickCount++ },
modifier = Modifier.padding(8.dp)
) {
Text(text = "Click Me")
}
Text(
text = "Button clicked $clickCount times",
style = MaterialTheme.typography.body1,
modifier = Modifier.padding(top = 16.dp)
)
}
}
Explanation:
- Button:
- The
onClick
lambda is triggered when the button is clicked. - In this example, we increment the
clickCount
state variable.
- Text:
- Displays the number of times the button was clicked.
- State Management:
remember
andmutableStateOf
are used to manage the click count state.
- Layout:
- The
Column
centers the button and the text vertically and horizontally.
Example with Different Button Styles
@Composable
fun StyledButtonExample() {
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
// Default Button
Button(onClick = { /* Do something */ }) {
Text("Default Button")
}
// Outlined Button
OutlinedButton(onClick = { /* Do something */ }) {
Text("Outlined Button")
}
// Text Button
TextButton(onClick = { /* Do something */ }) {
Text("Text Button")
}
// Button with Rounded Corners and Custom Color
Button(
onClick = { /* Do something */ },
colors = ButtonDefaults.buttonColors(backgroundColor = Color(0xFF6200EE)),
shape = RoundedCornerShape(16.dp),
modifier = Modifier.padding(8.dp)
) {
Text(
text = "Styled Button",
color = Color.White
)
}
}
}
Explanation of Styles:
- Default Button:
- A simple material-designed button.
- OutlinedButton:
- A button with an outlined border and no background.
- TextButton:
- A flat button with no border or background.
- Custom Styled Button:
- Uses
ButtonDefaults.buttonColors
to customize the background color. - The shape is adjusted using
RoundedCornerShape
.
How to Use:
- Add either
SimpleButtonExample()
orStyledButtonExample()
to thesetContent
block in yourMainActivity
.
Would you like to explore more about buttons, such as icons or custom animations?