Search code examples
androidkotlinandroid-jetpack-composevertical-alignmentscaffold

Jetpack Compose verticalArrangement to center of the Scaffold doesn't work


I am trying to get the text in my basic app centered vertically. I use a Column with verticalArrangement = Arrangement.Center, but it is still at the top of the screen:

Can you help me find out what am I missing?

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            HappyBirthday3Theme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    GreetingText(
                        message = "Happy Birthday Baruška!",
                        from = "From Dominika",
                        modifier = Modifier.padding(8.dp),
                    )
                }
            }
        }
    }
}

@Composable
fun GreetingText(message: String, from: String, modifier: Modifier = Modifier) {
    Column(
        verticalArrangement = Arrangement.Center,
        modifier = modifier,
    ) {
        Text(
            //Birthday message.
            text = message,
            fontSize = 100.sp,
            lineHeight = 116.sp,
            textAlign = TextAlign.Center,
        )
        Text(
            //From who it is sent.
            text = from,
            fontSize = 36.sp,
            modifier = Modifier
                .padding(16.dp)
                .align(alignment = Alignment.End),
        )
    }
}

@Preview(showBackground = true)
@Composable
fun BirthdayCardPreview() {
    HappyBirthday3Theme {
        GreetingText(message = "Happy Birthday Baruš!", from = "From Dominika")
    }
}

Solution

  • Your text is centered vertically, just only centered inside your Column, not the entire screen. You didn't specify a height for your Column so the Column is as small as possible, just large enough so the text fits. Since there is no additional space inside the Column there is no difference if you align the text to the top, the bottom, or if you center it.

    This changes if you explicitly set the height of the Column to something more that what would be necessary to fit the content. With this additional space it makes sense to specify an alignment, like bottom or center:

    Column(
        verticalArrangement = Arrangement.Center,
        modifier = modifier.fillMaxSize(),
    ) {
        // ...
    }
    

    fillMaxSize tells the Column to take up all the space that is available. It does not only specify to take up the entire height (which could be done with fillMaxHeight instead), it also takes up the entire width. This will prevent the same issue you had with the height to also appear with the width.