Android

Error while placing text to the leftmost and switch to the rightmost in the same row

ej503 2023. 2. 11. 23:57
@Composable
fun MainView(
    modifier: Modifier = Modifier,
    imageResourceId : Int,
) {
    ConstraintLayout(modifier = modifier.fillMaxSize()) {
        val (image) = createRefs()
        Image(
            painter = painterResource(id = imageResourceId),
            contentDescription = "empty",
            modifier = Modifier
                .constrainAs(image) {
                    linkTo(
                        start = parent.start,
                        end = parent.end,
                    )
                    width = Dimension.ratio("1:2")
                    height = Dimension.ratio("1:0.5")
                }
        )
    }
}

@Composable
fun SoundsList() {
    val sounds = listOf(
        "CAR HORN", "SIREN", "FIRE ALARM", "RINGTONE", "BARKING", "KNOCKING", "DOORBELL", "CRYING",
    )
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .fillMaxHeight(),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(
            text = "Sounds List",
            fontSize = 24.sp,
            modifier = Modifier.padding(35.dp),
            style = TextStyle(
            ), fontWeight = FontWeight.Black
        )
        LazyColumn(
            modifier = Modifier.height(500.dp)
        ) {
            items(sounds) { sound ->
                var selected1 by remember { mutableStateOf(false)}
                Rows(name = sound, change = selected1, onCheckedChange = {
                    selected1 = it
                })
                Divider()
            }
        }
    }
}

@Composable
private fun Rows(name:String, change:Boolean, onCheckedChange: (Boolean) -> Unit) {
    Row(
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        Text(text = name,
            modifier = Modifier
                .padding(15.dp)
                .weight(3f),
            textAlign = TextAlign.Start,
        )
        Switch(
            checked = change,
            onCheckedChange = onCheckedChange,
            colors = SwitchDefaults.colors(
                checkedThumbColor = Color.White,
                uncheckedThumbColor = Color.White,
                checkedTrackColor = Color.Green,
                uncheckedTrackColor = Color.Gray
            ),
            modifier = Modifier.weight(1f)
        )
    }
}

 

How to set text in the left side and switch in the right side?

 

오류 상황 : 처음에 text와 switch 사이에 Space()를 주어 간격을 일정하게 맞추려고 했지만, text 길이가 달라지면 switch의 위치까지 변하는 문제가 발생함

 

확인 사항: TextAlign을 Start로 설정하고, Text에 weight를 설정했다. 즉, 가중치 설정으로 해결했다.