Open In App

Switch Button in Android using Jetpack Compose

Last Updated : 29 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

A Switch or a Switch Button in Android is a UI element that is used to switch between two states upon click. It can be assumed as a Boolean button with two different values. Some states where you may find a Switch in your Android device can be Wi-fi ON and OFF, Bluetooth ON and OFF, Dark Mode and Light Mode, etc.

Switch Button in Android

In this article, we will show you how you could implement a Switch Button and check its CheckedState in Android using Jetpack Compose. Follow the below steps once the IDE is ready.

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. While choosing the template, select Empty Compose Activity. If you do not find this template, try upgrading the Android Studio to the latest version. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.

Step 2: Working with the MainActivity.kt file

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.

Kotlin




package com.geeksforgeeks.jcswitch
  
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
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.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
  
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            // Calling the composable function
            // to display element and its contents
            MainContent()
        }
    }
}
  
// Creating a composable 
// function to display Top Bar
@Composable
fun MainContent() {
    Scaffold(
        topBar = { TopAppBar(title = { Text("GFG | Switch", color = Color.White) }, backgroundColor = Color(0xff0f9d58)) },
        content = { MyContent() }
    )
}
  
// Creating a composable function to 
// create two Images and a spacer between them
// Calling this function as content 
// in the above function
@Composable
fun MyContent(){
  
    // Fetching the Local Context
    val mContext = LocalContext.current
  
    Column(Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
  
        // Declaring a boolean value for storing checked state
        val mCheckedState = remember{ mutableStateOf(false)}
  
        // Creating a Switch, when value changes,
        // it updates mCheckedState value
        Switch(checked = mCheckedState.value, onCheckedChange = {mCheckedState.value = it})
  
        // Adding a Space of 100dp height
        Spacer(modifier = Modifier.height(100.dp))
          
        // Creating a Button to display mCheckedState
        // value in a Toast when clicked
        Button(onClick = {
            Toast.makeText(mContext, mCheckedState.value.toString(), Toast.LENGTH_SHORT).show()
        },
            colors = ButtonDefaults.buttonColors(backgroundColor = Color(0XFF0F9D58)),
        ) {
            Text("Show Checked State", color = Color.White)
        }
    }
}
  
// For displaying preview in 
// the Android Studio IDE emulator
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    MainContent()
}


Output:

When you run the application you will see that the Switch is initially false. When you click the Button, it will display a Toast with ‘false’ written. Now, when you click on Switch, it becomes true and if the Button is clicked, it will display a Toast with ‘true’ written. You can see this happening in the below video of this application.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads