1

I can change the background color of 1 single button, by pressing it and updating the relevant State, as follows:

@Composable
fun makeButtons() {
    var isPressed by remember { mutableStateOf(false) }
    val color = if (isPressed) Color.Red else Color.Green

    Column {
        Button(
            onClick = { isPressed = !isPressed },
            colors = ButtonDefaults.buttonColors(backgroundColor = color)
        ) {
            Text("Btn")
        }
    }
}

But how can I locate a single button (i.e by its ID, or Text value) when all buttons are created dynamically (i.e in a for loop)?

@Composable
fun makeButtons() {
    var isPressed by remember { mutableStateOf(false) }
    val color = if (isPressed) Color.Red else Color.Green

    Column {
        for (i in 1..5) {
            Button(
                onClick = { isPressed = !isPressed },
                colors = ButtonDefaults.buttonColors(backgroundColor = color)
            ) {
                Text("Btn $i")
            }
        }
    }
}

I want to be able to change the background color of each Button, separately. Currently, if you run the above code, all will change color together, if you press any.

enter image description here enter image description here

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
Ali
  • 107
  • 1
  • 8
  • You want something like select one out of the 5 buttons or each has a different action on click? – Abhimanyu Feb 02 '22 at 13:46
  • Or something like checkboxes / toggle buttons / switch with ON and OFF states? – Abhimanyu Feb 02 '22 at 13:48
  • I want to be able to change the background color of each button separately, i,e when you click on Btn 2, it turns Red. If you click on it again, it turns Green. and the same for the rest of n buttons – Ali Feb 02 '22 at 13:48

1 Answers1

0

You can use a mutableStateListOf instead of mutableStateOf or you can simply define isPressed inside the for-cycle:

   for (i in 1..5) {
        var isPressed by remember { mutableStateOf(false) }
        val color = if (isPressed) Color.Red else Color.Green
        
        Button(
            onClick = { isPressed = !isPressed },
            colors = ButtonDefaults.buttonColors(backgroundColor = color)
        ) {
            Text("Btn $i")
        }
    }

enter image description here

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841