我们如何在 Jetpack Compose 中为每行使用切换按钮?

How we can use toggle button for per row in jetpack compose?

我正在尝试学习 Jetpack Compose,我的屏幕上有一个文本行,我想为每行使用切换按钮,但我不确定,如何在这个项目中添加切换按钮,我知道如何添加图像按钮,但我不确定如何在此处实现切换按钮,知道吗?

 @Composable
fun MainScreen() {

        Column(
            modifier = Modifier
                .fillMaxWidth(),
            horizontalAlignment = Alignment.CenterHorizontally

        ) {
  
        Column(
            modifier = Modifier
                .fillMaxHeight()
                .fillMaxWidth(),
            horizontalAlignment = Alignment.Start) {

            MainRow(
                name = "name1",
                )

            MainRow(
                name = "name2",

                )

            MainRow(
                name = "name3",

                )
            MainRow(
                name = "name4",

                )}}
   
@Composable
fun MainRow(
    name: String,


    ) {
    
    Row(
       
        verticalAlignment = Alignment.CenterVertically
    ) {


        Text(
            text = name,
            
        )}}

切换:

  Switch(
            modifier = Modifier.scale(1f),
            checked = checkedState.value,
            onCheckedChange = { checkedState.value = it },
            colors = SwitchDefaults.colors(
                checkedThumbColor = Color.Red,
                uncheckedThumbColor = Color.Green,
                checkedTrackColor = Color.Yellow,
                uncheckedTrackColor = Color.Black
            )
        )

您可以将行创建为

@Composable
private fun MainRow(name:String, change:Boolean, onCheckedChange: (Boolean) -> Unit) {

    Row(verticalAlignment = Alignment.CenterVertically) {

        Switch(
            checked = change,
            onCheckedChange = onCheckedChange,
            colors = SwitchDefaults.colors(
                checkedThumbColor = Color.Red,
                uncheckedThumbColor = Color.Green,
                checkedTrackColor = Color.Yellow,
                uncheckedTrackColor = Color.Black
            )
        )
        
        Text(text = name)
    }
}

并将其用作

    var selected1 by remember { mutableStateOf(false)}
    MainRow(name = "Row1", change = selected1, onCheckedChange = {
        selected1 = it
    })

   var selected2 by remember { mutableStateOf(false)}
    
    MainRow(name = "Row1", change = selected2, onCheckedChange = {
        selected2 = it
    })