In Jetpack Compose, you can use the Switch
composable to create a toggle switch. It’s simple to implement and commonly used for enabling/disabling features.
Basic Example of a Switch
@Composable
fun SwitchExample() {
var isChecked by remember { mutableStateOf(false) }
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(16.dp)
) {
Text(text = if (isChecked) "Switch is ON" else "Switch is OFF")
Spacer(modifier = Modifier.width(8.dp))
Switch(
checked = isChecked,
onCheckedChange = { isChecked = it }
)
}
}
Explanation:
- State Management:
isChecked
manages the on/off state of the switch.- The
onCheckedChange
lambda toggles the state.
- UI Elements:
Row
arranges theText
andSwitch
horizontally.Spacer
adds some space between the text and the switch.
Switch with Custom Colors
You can customize the Switch
colors using the colors
parameter.
@Composable
fun CustomSwitchExample() {
var isChecked by remember { mutableStateOf(false) }
Switch(
checked = isChecked,
onCheckedChange = { isChecked = it },
colors = SwitchDefaults.colors(
checkedThumbColor = Color.Green,
uncheckedThumbColor = Color.Red,
checkedTrackColor = Color.LightGray,
uncheckedTrackColor = Color.DarkGray
),
modifier = Modifier.padding(16.dp)
)
}
Explanation:
- SwitchDefaults.colors:
- Customize the thumb and track colors for the
checked
andunchecked
states.
Switch with a Label
To make it more informative, you can add a label or description.
@Composable
fun LabeledSwitchExample() {
var isChecked by remember { mutableStateOf(false) }
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.fillMaxSize()
) {
Text(text = "Enable Notifications")
Spacer(modifier = Modifier.height(8.dp))
Switch(
checked = isChecked,
onCheckedChange = { isChecked = it }
)
}
}
Animated Switch
Add a smooth color transition when toggling the switch.
@Composable
fun AnimatedSwitchExample() {
var isChecked by remember { mutableStateOf(false) }
val thumbColor by animateColorAsState(
targetValue = if (isChecked) Color.Green else Color.Red
)
Switch(
checked = isChecked,
onCheckedChange = { isChecked = it },
colors = SwitchDefaults.colors(
checkedThumbColor = thumbColor,
uncheckedThumbColor = thumbColor
),
modifier = Modifier.padding(16.dp)
)
}
Explanation:
- animateColorAsState:
- Smoothly transitions the thumb color between states.
How to Use:
- Add any of the above composables (
SwitchExample
,CustomSwitchExample
,LabeledSwitchExample
, orAnimatedSwitchExample
) in yoursetContent
block ofMainActivity
.
Would you like examples of switches in a list or as part of a form?