In Jetpack Compose, you can create a ToggleButton using Button
or IconButton
combined with state management to toggle between states.
Simple Toggle Button Example
@Composable
fun ToggleButtonExample() {
var isToggled by remember { mutableStateOf(false) }
Button(
onClick = { isToggled = !isToggled },
colors = ButtonDefaults.buttonColors(
backgroundColor = if (isToggled) Color.Green else Color.Red
),
modifier = Modifier.padding(16.dp)
) {
Text(
text = if (isToggled) "ON" else "OFF",
color = Color.White
)
}
}
Explanation:
- State Management:
isToggled
manages the state of the toggle button.- The state switches between
true
andfalse
on every click.
- Dynamic UI:
- The background color and text change based on the
isToggled
value.
Toggle Button with Icons
@Composable
fun IconToggleButtonExample() {
var isToggled by remember { mutableStateOf(false) }
IconButton(
onClick = { isToggled = !isToggled },
modifier = Modifier.padding(16.dp)
) {
Icon(
imageVector = if (isToggled) Icons.Default.Favorite else Icons.Default.FavoriteBorder,
contentDescription = if (isToggled) "Favorite" else "Not Favorite",
tint = if (isToggled) Color.Red else Color.Gray
)
}
}
Explanation:
- IconButton:
- Used to create a toggle button with an icon.
- Icons change dynamically based on the toggle state.
- Icons:
Icons.Default.Favorite
andIcons.Default.FavoriteBorder
are Material Design icons.
- Dynamic Tint:
- Icon color changes between red and gray depending on the state.
Toggle Button with Animation (Optional)
To enhance the experience, you can add animations using animateColorAsState
:
@Composable
fun AnimatedToggleButtonExample() {
var isToggled by remember { mutableStateOf(false) }
val backgroundColor by animateColorAsState(
targetValue = if (isToggled) Color.Green else Color.Red
)
Button(
onClick = { isToggled = !isToggled },
colors = ButtonDefaults.buttonColors(backgroundColor = backgroundColor),
modifier = Modifier.padding(16.dp)
) {
Text(
text = if (isToggled) "ON" else "OFF",
color = Color.White
)
}
}
Explanation:
- animateColorAsState:
- Animates the color transition between states.
- Smooth Transitions:
- The button background color transitions smoothly when toggled.
How to Use:
- Add one of the above composables (
ToggleButtonExample
,IconToggleButtonExample
, orAnimatedToggleButtonExample
) in thesetContent
block of yourMainActivity
.
Would you like more advanced toggle button examples, like grouped toggles or multi-selection toggles?