[FIXED] How to center elements inside a column in Jetpack Compose

Issue

How to center elements inside the first Column which is embedded inside a Row:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            MaterialTheme {
                Row {
                    Column(modifier = LayoutPadding(top = 16.dp)) {
                        Text(text = "Centered ", style = TextStyle(fontSize = 30.sp, fontWeight = FontWeight.Bold))
                    }
                    Column {
                        Text(text = "Line One ", style = TextStyle(fontSize = 30.sp, fontWeight = FontWeight.Bold))
                        Text(text = "Line Two ", style = TextStyle(fontSize = 30.sp, fontWeight = FontWeight.Bold))
                    }
                 }
             }
         }
     }
}

In this example I hardcoded padding, but was not able to figure out how to center the elements out of the box. If there is no such an option, how can I get a height of the whole Row?

Solution

You can use the Modifier.align in your Column

Row (){
    Column( modifier = Modifier.align(Alignment.CenterVertically)){
        Text(text = "Centered ", style = textStyle)
    }
    Column {
        Text(text = "Line One ", style = textStyle)
        Text(text = "Line Two ", style = textStyle)
    }
}

enter image description here

or you can use the verticalAlignment = Alignment.CenterVertically in the Row element:

Row (verticalAlignment = Alignment.CenterVertically){
    Column(){
        Text(text = "Centered ", style = textStyle)
    }
    Column() {
        Text(text = "Line One ", style = textStyle)
        Text(text = "Line Two ", style = textStyle)
    }
}

Answered By – Gabriele Mariotti

Answer Checked By – Pedro (FixeMe Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *