Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Jetpack compose dynamic button ID

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here
enter image description here

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading