Sunday, March 7, 2021

jetpack compose - How to use Switch

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()
    }
}