Jetpack compose dynamic button ID

1k Views Asked by At

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

1

There are 1 best solutions below

1
Gabriele Mariotti On BEST ANSWER

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