How to add Toggle Button in Android Jetpack Compose

By Mohammed Rashid •  November 19th, 2022 • 

The toggle button or the switch button is a UI component through which users can turn on or off a particular option. The toggle button is always seen on the settings screen. Let’s learn how to add a simple switch button in Android using Jetpack Compose.

The Switch in compose helps to create a toggle button. It accepts parameters such as checked, onCheckedChange, modifier, enabled, colors, etc. Following is the code snippet to add Switch.

@Composable
fun SwitchExample() {
    val checked = remember { mutableStateOf(true) }
    Switch(
        checked = checked.value,
        onCheckedChange = { checked.value = it },
    )
}

Following is the output.

switch jetpack compose

Following is the complete code for reference.

package com.example.myapplication

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.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.myapplication.ui.theme.MyApplicationTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyApplicationTheme {
                Surface(
                    color = MaterialTheme.colors.background,
                    modifier = Modifier.fillMaxSize()
                ) {
                    SwitchExample()
                }
            }
        }
    }
}

@Composable
fun SwitchExample() {
    val checked = remember { mutableStateOf(true) }
    Switch(
        checked = checked.value,
        onCheckedChange = { checked.value = it },
    )
}

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    MyApplicationTheme {
        SwitchExample()
    }
}

That’s how you add a switch or toggle in Jetpack Compose.

Mohammed Rashid

Keep Reading