Jetpack Compose: Box gravity example

Introduction

This example demonstrates the use of Jetpack Compose’s Box composable in an Android app to explore alignment and gravity within a UI. The Kotlin-based example showcases how to structure a simple user interface, positioning elements within a Box using different alignment settings. The sample app is designed to help Android developers understand how Box works in Jetpack Compose and how to apply various layout and alignment options effectively. It uses simple components, including a Scaffold, to wrap the layout and provide a consistent structure with a top bar.

Structure and Setup

The starting point of this project is the MainActivity, which extends AppCompatActivity. Upon creation of the activity, the setContent function is called to initiate the composable functions. The core layout is defined by the GetScaffold() composable, which is responsible for organizing the entire screen content. Within this scaffold, there is a TopAppBar that gives the app a standard navigation bar at the top. The rest of the screen's content is handled by the MainContent() function, where the layout is designed using a Column containing multiple Box elements.

The Scaffold and App Bar

The Scaffold composable is used to manage the overall layout of the app, providing areas for the top bar, bottom bar, floating action button, and content. In this example, the top bar is created using the TopAppBar composable, which contains a Text widget that displays the title "Compose - Box Gravity" with a custom background color. This ensures that the UI has a familiar app structure while focusing on the content aligned within the main area.

Layout with Column and Box

The core of the user interface is managed inside the MainContent() composable, which is responsible for arranging the Box elements vertically using a Column. The Column is designed to take up the full screen space (fillMaxSize()) and ensures that the Box elements are evenly spaced using the Arrangement.SpaceEvenly parameter. The alignment of the content within each Box is a key feature of this example, showcasing how Jetpack Compose manages gravity or alignment through the contentAlignment property.

Understanding Box Alignment

The Box composable is a powerful container that allows for precise control over the positioning of its content. In this example, three different Box components demonstrate various alignments:

  • Center Alignment: The first Box centers its text content both vertically and horizontally. This is achieved by setting contentAlignment = Alignment.Center, which is useful for creating balanced layouts where content needs to be symmetrically aligned.

  • Center Vertically, Start Horizontally: The second Box demonstrates vertical centering combined with left alignment. The contentAlignment = Alignment.CenterStart parameter ensures the text is centered vertically but aligned to the start of the container horizontally, providing a clear example of how to manage mixed alignments.

  • Top Center Alignment: In the third Box, the content is aligned at the top center of the container. This is specified using contentAlignment = Alignment.TopCenter, allowing for a different layout where the text begins at the top but remains centered horizontally.

Each Box is styled with distinct padding, background colors, and rounded corners, making it visually easy to distinguish the different alignment properties.

Previewing the Layout

A ComposablePreview() function is included to allow easy previewing of the UI in Android Studio's preview window. Although it’s commented out in this example, this function is an essential part of the Compose development workflow, enabling developers to view and adjust layouts without needing to run the app on a device or emulator.

Summary

In summary, this example serves as an excellent introduction to Jetpack Compose’s Box composable and how gravity and alignment can be managed within layouts. By utilizing different Alignment properties, developers can control the positioning of elements inside a Box and create flexible UI designs. The combination of Scaffold, Column, and Box in this example demonstrates a clear and modular approach to UI development in Jetpack Compose, offering both simplicity and versatility. Understanding these basics is critical for building complex and dynamic user interfaces in modern Android applications.


MainActivity.kt

package com.cfsuman.jetpackcompose

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
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.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp

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

        setContent {
            GetScaffold()
        }
    }


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


    @Composable
    fun MainContent(){
        Column(
            modifier = Modifier
                .fillMaxSize(),
            verticalArrangement = Arrangement.SpaceEvenly,
            horizontalAlignment = Alignment.CenterHorizontally
        ){
            Box(
                Modifier
                    .padding(12.dp)
                    .fillMaxWidth()
                    .height(150.dp)
                    .clip(RoundedCornerShape(12.dp))
                    .background(Color(0xFFB2FFFF))
                    .padding(12.dp),
                contentAlignment = Alignment.Center
            ){
                Text(
                    text = "Gravity Center",
                    style = MaterialTheme.typography.caption
                )
            }

            Box(
                Modifier
                    .padding(12.dp)
                    .fillMaxWidth()
                    .height(150.dp)
                    .clip(RoundedCornerShape(12.dp))
                    .background(Color(0xFFB2EC5D))
                    .padding(12.dp),
                contentAlignment = Alignment.CenterStart
            ){
                Text(
                    text = "Gravity Center Vertically",
                    style = MaterialTheme.typography.caption
                )
            }

            Box(
                Modifier
                    .padding(12.dp)
                    .fillMaxWidth()
                    .height(150.dp)
                    .clip(RoundedCornerShape(12.dp))
                    .background(Color(0xFFD6CADD))
                    .padding(12.dp),
                contentAlignment = Alignment.TopCenter
            ){
                Text(
                    text = "Gravity Center Horizontally",
                    style = MaterialTheme.typography.caption
                )
            }
        }
    }


    @Preview
    @Composable
    fun ComposablePreview(){
        //GetScaffold()
    }
}
More android jetpack compose tutorials