Jetpack Compose Switch Button (with Examples)

Jetpack Compose Switch Button

In this article, we will explore Switch Button in Jetpack Compose with the help of examples.

Prerequisites:

What is Switch in Android Jetpack Compose?

The switch (or switch button) represents two states – on and off. When we tap on it, it toggles the state. We mostly use the switch in the app’s settings screen.

Example:

switch example usage

Anatomy of Switch Button:

A switch has two properties – thumb and track.

1. Thumb
2. Track

For this article, create a MyUI() composable in the MainActivity, and call it from the onCreate() method.

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
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
private fun MyUI() {
    
}

We will write our code in the MyUI() composable.

Jetpack Compose provides Switch() API. It looks like this:

@Composable
@OptIn(ExperimentalMaterialApi::class)
fun Switch(
    checked: Boolean,
    onCheckedChange: ((Boolean) -> Unit)?,
    modifier: Modifier = Modifier,
    enabled: Boolean = true,
    interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
    colors: SwitchColors = SwitchDefaults.colors()
)

checked – Whether the switch is on or off.

onCheckedChange – A lambda that gets called whenever the state is changed. It includes a boolean that indicates whether the switch is on or off.

modifier – To modify the layout of the switch.

enabled – If the switch is enabled or not.

interactionSource – To customize the interactions. For example, you can disable the ripple effect.

colors – To change the Switch default colors.

Simple Switch Example:

For a basic switch, checked and onCheckedChange parameters are mandatory.

@Composable
private fun MyUI() {
    var switchOn by remember {
        mutableStateOf(false)
    }

    Switch(
        checked = switchOn,
        onCheckedChange = { switchOn_ ->
            switchOn = switchOn_
        }
    )
}

Output:

switch example

Switch Colors:

We can customize the thumb and track colors using the SwitchDefaults.colors() method.

public final fun colors(
    checkedThumbColor: Color,
    checkedTrackColor: Color,
    checkedTrackAlpha: Float,
    uncheckedThumbColor: Color,
    uncheckedTrackColor: Color,
    uncheckedTrackAlpha: Float,
    disabledCheckedThumbColor: Color,
    disabledCheckedTrackColor: Color,
    disabledUncheckedThumbColor: Color,
    disabledUncheckedTrackColor: Color
): SwitchColors

Example:

@Composable
private fun MyUI() {
    var switchOn by remember {
        mutableStateOf(false)
    }

    Switch(
        checked = switchOn,
        onCheckedChange = { switchOn_ ->
            switchOn = switchOn_
        },
        colors = SwitchDefaults.colors(
            checkedThumbColor = Color.Green,
            checkedTrackColor = Color.Magenta
        )
    )
}

Output:

switch colors

Changing the Switch Size:

There is no option to change the switch size, but we can use the Modifier’s scale method to scale it.

@Composable
private fun MyUI() {
    var switchOn by remember {
        mutableStateOf(false)
    }

    Switch(
        modifier = Modifier.scale(scale = 2f),
        checked = switchOn,
        onCheckedChange = { switchOn_ ->
            switchOn = switchOn_
        }
    )
}

Output:

switch size

Switch with Label/Text:

Switch() composable doesn’t have a parameter to add a label. But, we can put the Switch() and Text() in a Column() to include the label.

@Composable
private fun MyUI() {
    var switchOn by remember {
        mutableStateOf(false)
    }

    Column(
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Switch(
            checked = switchOn,
            onCheckedChange = { switchOn_ ->
                switchOn = switchOn_
            }
        )
        Text(text = if (switchOn) "ON" else "OFF")
    }
}

Output:

Switch with label

How to Change Switch Track Width and Stroke?

There is no way to change them. But, we can easily create a custom switch using the Box or Canvas API.

Example:

switch with icon on
switch with icon off

I have made it using the Box() API. If you like it, check out all the custom switch designs here.

This is all about the switch button in Android Jetpack Compose. I hope you have learned something new. If you have any doubts, comment below.

Related:

References:

Leave a Comment