Home > Enterprise >  Kotlin JetPack Compose, changing color of dynamic composed buttons
Kotlin JetPack Compose, changing color of dynamic composed buttons

Time:12-14

So I have this code:

@Composable
fun Botones(strings: MutableMap<String, Color>) {

    Column{
        strings.forEach { color ->
            Button(
                onClick = {
                    // Update the button color
                    if (color.value == Color.Red) {
                        color to Color.Blue
                    } else if (colo.value == Color.Blue) {
                        color to Color.Green
                    } else {
                        color to Color.Red
                    }
                },
                colors = ButtonDefaults.buttonColors(backgroundColor = color.value)
            ) {
                // Place the string in the buton, set font color to white
                Text(colorsito.key, color = Color.White)
            }
        }
    }
}

Initially, all colors should be red, and every time a button is clicked, it should change its color, while the other buttons should remain the same. I don't necesarely need to use a mutable map, what I want is, for every string, make a red button, that when clicked, changes it color depending on which color it had before. Problem is I can't get it to work because apparently it doesn't recompose. I tried using remember, but it doesn't detect when a value of a mutable map changes, and I sincerely don't know how to get it to work. Help would be much appreciated, I've been googlin' for a while with 0 results, and not even chatGPT was able to get it to work correctly.

EDIT: So magically Copilot suggested this, and it works, but I would very much appreciate if someone could explain why:

@Composable
fun MyComposable(items: List<String>) {
    var itemsio by remember { mutableStateOf(items) }
    LazyColumn {
        items(itemsio.size) { index ->
            var item = itemsio[index]
            var color by remember { mutableStateOf(Color.Red) }
            Text(item, modifier = Modifier.background(color).clickable(
                    interactionSource = remember {MutableInteractionSource()},
                    indication = null
                ) {
                    if (color == Color.Red) {
                        color = Color.Blue
                    } else if (color == Color.Blue) {
                        color = Color.Green
                    } else {
                        color = Color.Red
                    }
                }
            )
        }
    }

interactionSource and indication makes it work? but why

CodePudding user response:

It looks like CoPilot or chatGPT need some time to take our jobs

  • Related