Friday, September 24, 2021

jetpack compose - Box center alignment

Compose Box Center Alignment
The Box is a very popular layout widget in a jetpack compose android application. Box allows us to put a single element inside it. So, Box is a single-child container. When Box’s child widget is much smaller than the Box widget itself, the developer needs to align it inside the Box component. Such as we have a Box widget whose size is fill the available area and we have a Button widget inside the Box widget, in this situation we have to align our Box child widget as per our requirement.

This android development tutorial shows you how you can center align a component inside a Box widget. Box center alignment is so easy to implement in a jetpack compose application. Let us describe the code, and how we dot it.

At first, we put a Box layout widget in a composable function. Next, we set the Box modifier to fill the maximum available size. We also put a padding value and clip to make it rounded corners. Then we set the Box’s ‘contentAlignment’ property value to ‘Alignment.Center’ which means we specify the Box content alignment to the center position.

The ‘contentAlignment’ is the main property to make a Box content center aligned. Finally, we put a TextView inside the Box layout widget to show it at the center position of the Box widget. The following code and screenshots will help you to better understand the functionality.

package com.cfsuman.jetpackcompose

import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {

        setContent {

    fun GetScaffold(){
            topBar = {TopAppBar(
                title = {Text(
                    "Compose - Box Center",
                    color = Color.White)},
                backgroundColor = Color(0xFF58427C)) },
            content = {MainContent()},
            backgroundColor = Color(0xFFEDEAE0)

    fun MainContent(){
            contentAlignment = Alignment.Center
                text = "Alignment Center",
                style = MaterialTheme.typography.h6

    fun ComposablePreview(){