Jetpack Compose: How to use Switch

Introduction

This Android Jetpack Compose example demonstrates how to implement and use the Switch component in a Kotlin-based Android application. Switches are essential UI components that allow users to toggle between two states, typically on or off, and are often found in settings or forms where users need to make binary choices. This example showcases the simplicity and power of using Jetpack Compose for building modern UIs in Android development, emphasizing its declarative approach.

In this example, you'll find how to create two separate switches with different states and color customizations. The code is structured using Jetpack Compose's core features such as @Composable functions, state management with remember, and UI layout building with the Column, Row, and Text composables. By the end of this description, you will understand the core components and structure used to handle state changes and customize the appearance of switches in an Android app.

Main Content Setup

The MainActivity.kt file serves as the entry point of the application. It starts by setting up the content within the onCreate() method, where the MainContent() composable function is invoked. This is a fundamental step in a Compose-based app, where instead of using XML layouts, UI components are created using composable functions and directly injected into the activity using setContent().

The core of the UI is handled inside the MainContent() function. In this function, two Switch components are defined, each tied to its respective state using Jetpack Compose’s remember and mutableStateOf functions. These functions enable the state of the switches to be remembered and updated dynamically as users interact with them. The first switch is initialized to a true state (on), while the second is initialized to false (off).

Switch Layout and State

Each Switch is placed inside a Row composable, which helps in arranging UI components horizontally. A Text composable is also placed beside each switch to display its current state (either "true" or "false"). The Switch itself is controlled by the checked parameter, which reads the current state from the checkedState variable, and the onCheckedChange parameter updates this state when the user toggles the switch.

To provide padding and alignment, modifiers are extensively used throughout the layout. For example, Modifier.padding() ensures that there’s sufficient space around each switch, while horizontalAlignment inside the Column composable ensures that the child elements are centered horizontally. Additionally, a Spacer is placed between the switch and the text to add extra space and prevent the components from appearing too close together.

Customizing the Second Switch

The second switch showcases how to customize the appearance of a switch in Jetpack Compose. Using the SwitchDefaults.colors() function, the example changes the thumb and track colors for both checked and unchecked states. When the switch is toggled on, the thumb changes to a teal green color (0xFF00CC99), and the track turns to a lighter green (0xFF7BB661). When the switch is off, the thumb and track turn into shades of pink and red. This customization demonstrates the flexibility of Compose in designing visually appealing and interactive components.

Previewing the UI

Finally, the code includes a @Preview annotation with a ComposablePreview() function. This function allows developers to preview the UI directly within Android Studio without deploying it on a physical device or emulator. Although the MainContent() function is commented out in the preview function, it serves as a placeholder to showcase how you can quickly toggle between writing and previewing the UI in the development process.

Conclusion

This Kotlin example highlights how Jetpack Compose simplifies UI development for Android. By using a declarative approach, developers can build flexible and dynamic interfaces with less boilerplate code compared to traditional XML-based UI layouts. The use of state management through remember and mutableStateOf ensures that UI components, like switches, respond to user interactions seamlessly.

Additionally, the ability to customize components, such as the switch colors, demonstrates the power of Jetpack Compose in creating modern, interactive, and visually consistent applications. This example lays the foundation for more complex UIs and showcases how intuitive it is to work with Jetpack Compose’s powerful toolset.


MainActivity.kt

package com.cfsuman.jetpackcompose

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            MainContent()
        }
    }


    @Composable
    fun MainContent(){
        val checkedState = remember { mutableStateOf(true) }
        val checkedState2 = remember { mutableStateOf(false) }

        Column(
            Modifier
                .background(Color(0xF5F5F5))
                .fillMaxSize()
                .padding(16.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Row(
                Modifier.padding(16.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Switch(
                    checked = checkedState.value,
                    onCheckedChange = { checkedState.value = it }
                )
                Spacer(modifier = Modifier.requiredWidth(16.dp))
                Text(
                    "${checkedState.value}",
                    fontSize = 25.sp
                )
            }

            Row(
                Modifier.padding(16.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Switch(
                    checked = checkedState2.value,
                    onCheckedChange = { checkedState2.value = it },
                    colors = SwitchDefaults.colors(
                        checkedThumbColor = Color(0xFF00CC99),
                        checkedTrackColor = Color(0xFF7BB661),
                        uncheckedThumbColor = Color(0xFFE4717A),
                        uncheckedTrackColor = Color(0xFFFFA6C9)
                    )
                )
                Spacer(modifier = Modifier.requiredWidth(16.dp))
                Text(
                    "${checkedState2.value}",
                    fontSize = 25.sp
                )
            }
        }
    }


    @Preview
    @Composable
    fun ComposablePreview(){
        //MainContent()
    }
}
More android jetpack compose tutorials