Home > Software design >  How to move object within Row to edge of screen in Jetpack Compose
How to move object within Row to edge of screen in Jetpack Compose

Time:06-13

I've made a Row containing 2 different items but I want the item on the right to be positioned on the edge of the screen. I tried using weights with the weight modifiers (modifier = Modifier.weight(...f)) but the results are not accurate enough. I also couldn't find any horizontal alignment features.

In the attached screenshot there is still plenty of space to the right of the Switch that can be used to move it to the edge of the screen (on the right).

Row(modifier = Modifier.fillMaxWidth()) {
    Text(text = "My custom switch", modifier = Modifier.weight(1f))
    Switch(modifier = Modifier.weight(1f))
}

enter image description here

CodePudding user response:

Using weight on first composable inside of Row:

var switchState by remember { mutableStateOf(value = false) }

Row(
    modifier = Modifier.fillMaxWidth(),
    verticalAlignment = Alignment.CenterVertically
) {
    Text(
        modifier = Modifier.weight(weight = 1f),
        text = "My switch"
    )

    Switch(
        checked = switchState,
        onCheckedChange = { switchState = it }
    )
}

Using SpaceBetween on Row:

var switchState by remember { mutableStateOf(value = false) }
                        
Row(
    modifier = Modifier.fillMaxWidth(),
    horizontalArrangement = Arrangement.SpaceBetween,
    verticalAlignment = Alignment.CenterVertically
) {
    Text(text = "My switch")

    Switch(
        checked = switchState,
        onCheckedChange = { switchState = it }
    )
}

You can apply a background to Text and Switch to see the difference involved in these two implementations.

With weight:
enter image description here

With SpaceBetween:
enter image description here

CodePudding user response:

You could try something like:

    Row(modifier = Modifier.fillMaxWidth()) {
    Text(text = "My custom switch", modifier = Modifier.weight(1f))
    Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.CenterEnd){
        Switch(checked = true, onCheckedChange = )
            }
        }
    }

Maybe change the .fillmaxwidth of the modifier, but contentAlignment is what you are looking for I think.

  • Related