user2892437
user2892437

Reputation: 1251

Android Compose - Align center one composable only in Column?

In Compose, you can align center all composables in a Column widget by doing the following:

Column(
        modifier = Modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally
) {
        Text(
                text = "First item",
                modifier = Modifier.padding(16.dp)
        )
        Text(
                text = "Second item",
                modifier = Modifier.padding(16.dp)
        )
        Text(
                text = "Third item",
                modifier = Modifier.padding(16.dp)
        )
}

However, what if I only want to center the first composable?

Upvotes: 2

Views: 1741

Answers (2)

Alejandro Casanova
Alejandro Casanova

Reputation: 3681

There are some cases where if you use .fillMaxWidth(), like in the accepted solution, the composable view can grow out of proportion (in this case since it is a Text) there are no problems and we actually profit from the gravity of the actual text inside the Text composable. For example I've experienced this issue with a CircularProgressIndicator.

The problem is that we are not really "centering" the composable we need to, but actually making the "non-centered" views to occupy all the available horizontal space and telling the column to center everything inside, kind of hacking our way into the desired effect which happens to work in this particular scenario.

In my oppinion the below solution would be a little bit mor scalable and less verbose, actually centering the view we need to be centered and avoiding undesired effects due to changing the rest of the views inside the column. I hope it helps!

    Column(
        modifier = Modifier.fillMaxSize()
    ) {
        Text(
            text = "First item - centered",
            modifier = Modifier
                .align(Alignment.CenterHorizontally)
                .padding(16.dp)
        )
        Text(
            text = "Second item",
            modifier = Modifier.padding(16.dp).fillMaxWidth()
        )
        Text(
            text = "Third item",
            modifier = Modifier.padding(16.dp).fillMaxWidth()
        )
    }

Upvotes: 0

Chris
Chris

Reputation: 5191

I think this should work for you

Column(
        modifier = Modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(
            text = "First item",
            modifier = Modifier.padding(16.dp)
        )
        Text(
            text = "Second item",
            modifier = Modifier.padding(16.dp).fillMaxWidth()
        )
        Text(
            text = "Third item",
            modifier = Modifier.padding(16.dp).fillMaxWidth()
        )
    }

Sample Render

Upvotes: 2

Related Questions