Search code examples
android-jetpack-composeandroid-jetpack

Unable to vertically center a Row composable children using android jetpack compose


I am an android developper and I am beginning with jetpack compose. I was following a tutorial and i've encountered a problem . I cannot center vertically a row child using verticalAlignment = Alignment.CenterVertically . There is impact on the preview screen . Here is the code :

   @Composable
fun HorizontalScreen(){

    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceEvenly,
        verticalAlignment = Alignment.CenterVertically
    ) {

        Text(text = "Text 1")
        Text(text = "Text 2")
        Text(text = "Text 3")
        Text(text = "Text 4")

    }

}


@Preview(showBackground = true, showSystemUi = true)
@Composable
fun HorizontalScreenPreview(){
    HorizontalScreen()
}

Solution

  • As pointed out in a comment, when you only do

    modifier = Modifier.fillMaxWidth()
    

    the Column

    • fills the maximum width of the screen
    • and by default adjusts its height to wrap the content.

    Because the Column already perfectly wraps its children, there is no visible difference when you use verticalAlignment = Alignment.CenterVertically. So change your code to

    modifier = Modifier.fillMaxWidth().fillMaxHeight()
    // or simply
    // modifier = Modifier.fillMaxSize()
    

    to see the expected verticalAlignment behaviour.

    enter image description here