androidkotlinandroid-jetpack-composeandroid-togglebutton

How we can use toggle button for per row in jetpack compose?


I am try to learn jetpack compose, and I have a text row in my screen, I want to use toggle button for per row, but I am not sure, how can I add toggle button in this project, I know how to add image button, but I am not sure how implement toggle button in here, any idea?

 @Composable
fun MainScreen() {

        Column(
            modifier = Modifier
                .fillMaxWidth(),
            horizontalAlignment = Alignment.CenterHorizontally

        ) {
  
        Column(
            modifier = Modifier
                .fillMaxHeight()
                .fillMaxWidth(),
            horizontalAlignment = Alignment.Start) {

            MainRow(
                name = "name1",
                )

            MainRow(
                name = "name2",

                )

            MainRow(
                name = "name3",

                )
            MainRow(
                name = "name4",

                )}}
   
@Composable
fun MainRow(
    name: String,


    ) {
    
    Row(
       
        verticalAlignment = Alignment.CenterVertically
    ) {


        Text(
            text = name,
            
        )}}

toggle:

  Switch(
            modifier = Modifier.scale(1f),
            checked = checkedState.value,
            onCheckedChange = { checkedState.value = it },
            colors = SwitchDefaults.colors(
                checkedThumbColor = Color.Red,
                uncheckedThumbColor = Color.Green,
                checkedTrackColor = Color.Yellow,
                uncheckedTrackColor = Color.Black
            )
        )

Solution

  • You can create your row as

    @Composable
    private fun MainRow(name:String, change:Boolean, onCheckedChange: (Boolean) -> Unit) {
    
        Row(verticalAlignment = Alignment.CenterVertically) {
    
            Switch(
                checked = change,
                onCheckedChange = onCheckedChange,
                colors = SwitchDefaults.colors(
                    checkedThumbColor = Color.Red,
                    uncheckedThumbColor = Color.Green,
                    checkedTrackColor = Color.Yellow,
                    uncheckedTrackColor = Color.Black
                )
            )
            
            Text(text = name)
        }
    }
    

    And use it as

        var selected1 by remember { mutableStateOf(false)}
        MainRow(name = "Row1", change = selected1, onCheckedChange = {
            selected1 = it
        })
    
       var selected2 by remember { mutableStateOf(false)}
        
        MainRow(name = "Row1", change = selected2, onCheckedChange = {
            selected2 = it
        })