NewPartizal
NewPartizal

Reputation: 1104

How can I implement Material3 Switch component in Material compose?

I'm using Material but I need to use Material3 for the Switch toggle button component. Switch component is appearing When I use Switch component in Material

code:

  var checked by remember { mutableStateOf(true) }
            Switch(
                modifier = Modifier.semantics { contentDescription = "Demo" },
                checked = checked,
                onCheckedChange = { checked = it })

enter image description here

But I want it to look like below image. I want the toggle on switch button to appear inside the component

enter image description here

this is Material3 Switch component code in Official Android developer documents

import androidx.compose.material3.Switch
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.semantics.semantics

var checked by remember { mutableStateOf(true) }
Switch(
    modifier = Modifier.semantics { contentDescription = "Demo" },
    checked = checked,
    onCheckedChange = { checked = it })

both are the same code but they have different Material version so They have different appearance as you can see the images.

Upvotes: 0

Views: 1531

Answers (2)

m.reiter
m.reiter

Reputation: 2525

Depending on which material version you use, your switch will be styled differently:


Material(2)

  • import androidx.compose.material.Switch
  • from library androidx.compose.material:material

enter image description here


Material3

  • import androidx.compose.material3.Switch
  • from library androidx.compose.material3:material3

enter image description here

Upvotes: 0

NewPartizal
NewPartizal

Reputation: 1104

I figured this out by making a custom toggle button like this: Problem is solved:)

@Composable
fun CustomToggleButton(
    selected: Boolean,
    modifier: Modifier = Modifier, 
    onUpdate: (Boolean) -> Unit
) {

    Card(
        modifier = modifier
            .width(50.dp)
            .clickable {
                onUpdate(!selected)
            }, shape = RoundedCornerShape(16.dp), elevation = 0.dp
    ) {
        Box(
            modifier = Modifier.background(
                if (selected) DarkPink else LightPink.copy(0.4f)
            ), contentAlignment = if (selected) Alignment.TopEnd else Alignment.TopStart
        ) {
            CheckCircle(modifier = Modifier.padding(5.dp))
        }
    }

}

var isToggle by remember { mutableStateOf(false) }
        
                     Box(
                        modifier = Modifier.fillMaxSize(),
                        contentAlignment = Alignment.Center
                    ) {
                        CustomToggleButton(selected = isToggle) {
                            isToggle = it
                        }
                    }

Upvotes: 0

Related Questions