0
0
Android Kotlinmobile~5 mins

Box layout in Android Kotlin

Choose your learning style9 modes available
Introduction

A Box layout lets you stack views on top of each other in the same space. It helps to place items overlapping or layered.

When you want to put a text label over an image.
When you want to show a button on top of a colored background.
When you want to layer multiple views in the same area.
When you want to create a badge or icon on top of another view.
Syntax
Android Kotlin
Box(modifier = Modifier.fillMaxSize()) {
    // child views here
}

The Box is a container that stacks children.

Use Modifier to control size and position.

Examples
This stacks two texts. The second text is placed at the bottom right.
Android Kotlin
Box {
    Text("Hello")
    Text("World", modifier = Modifier.align(Alignment.BottomEnd))
}
A box with fixed size containing a button.
Android Kotlin
Box(modifier = Modifier.size(100.dp)) {
    Button(onClick = {}) {
        Text("Click")
    }
}
Sample App

This app shows a blue square in the center with a button labeled "Press Me" on top of it. The button is layered over the blue box using Box layout.

Android Kotlin
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            Box(modifier = Modifier.fillMaxSize()) {
                Box(
                    modifier = Modifier
                        .size(200.dp)
                        .background(Color.Blue)
                        .align(Alignment.Center)
                )
                Button(
                    onClick = {},
                    modifier = Modifier.align(Alignment.Center)
                ) {
                    Text("Press Me")
                }
            }
        }
    }
}
OutputSuccess
Important Notes

Children in a Box are drawn in order, so later children appear on top.

You can use Modifier.align() to position children inside the Box.

Box is useful for layering but not for arranging items side by side or vertically.

Summary

Box layout stacks views on top of each other.

Use Modifier.align() to position children inside the Box.

Great for overlays, badges, or layered UI elements.