Search code examples
androidandroid-jetpack-composeandroid-jetpack-compose-layoutandroid-compose-layout

How to combine Arrangement.spacedBy() and Arrangement.Center in a Row.horizontalArrangement


Is it possible to combine Arrangement.spacedBy(16.dp) and Arrangement.Center in a Row.horizontalArrangement?

What I would like to do is to center the content horizontally and also set a default spacing of 16.dp.

I know that I can combine the Row and a Box to achieve the same result but I was wondering if can be done with just he Row's properties.

    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.Center, // I would like to add the .spacedBy(16.dp), keeping the Center arrangement 
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Text(
            text = stringResource(R.string.generic_error_pagination),
            style = MaterialTheme.typography.subtitle1,
            color = MaterialTheme.colors.textSecondary,
        )
        OutlinedButton(onClick = onClick) {
            Text(stringResource(id = R.string.retry_button))
        }
    }

Solution

  • Use the spacedBy variant with the alignment parameter:

    An alignment can be specified to align the spaced children horizontally inside the parent

        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement
                .spacedBy(
                    space = 16.dp, 
                    alignment = Alignment.CenterHorizontally
                ),
            verticalAlignment = Alignment.CenterVertically,
        )
    

    enter image description here