【问题标题】:Jetpack compose dynamic button IDJetpack 撰写动态按钮 ID
【发布时间】:2022-11-22 10:18:54
【问题描述】:

我可以通过按下并更新相关状态来更改 1 个单个按钮的背景颜色,如下所示:

@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")
        }
    }
}

但是,当所有按钮都是动态创建的(即在 for 循环中)时,如何定位单个按钮(即通过其 ID 或文本值)?

@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")
            }
        }
    }
}

我希望能够分别更改每个按钮的背景颜色。目前,如果你运行上面的代码,如果你按下任何一个,所有的颜色都会一起改变。

【问题讨论】:

  • 您想要从 5 个按钮中选择一个按钮或每个按钮在单击时具有不同的操作?
  • 或类似复选框/切换按钮/具有 ON 和 OFF 状态的开关?
  • 我希望能够分别更改每个按钮的背景颜色,即当您单击 Btn 2 时,它会变成红色。如果再次单击它,它会变为绿色。其余 n 个按钮也一样

标签: android android-jetpack-compose android-compose-button


【解决方案1】:

您可以使用 mutableStateListOf 而不是 mutableStateOf 或者您可以简单地在 for 循环中定义 isPressed

   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")
        }
    }

【讨论】:

  • 哇!正是我要找的...非常感谢!伟大的
猜你喜欢
  • 2022-06-25
  • 1970-01-01
  • 2021-07-12
  • 1970-01-01
  • 1970-01-01
  • 2020-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多