Home > Blockchain >  Android Compose - Align center one composable only in Column?
Android Compose - Align center one composable only in Column?

Time:10-21

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?

CodePudding user response:

You can wrap the first composable inside another Column and apply center alignment only to that one as follows:

Column(
        modifier = Modifier.fillMaxSize()
) {
    Column(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)
    )
}

CodePudding user response:

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

  • Related