Compose Layout Basics and UI Control
约 310 字大约 1 分钟
Android
2025-12-23
1. Background
In practice, we found that when permission was not granted, the “Request Camera Permission” button would stretch across the whole screen. That clearly did not match the intended design.
To make the button stay centered with a fixed size, we need to understand Compose layout containers, alignment, and the Modifier.
This note focuses on how to control layout and UI element size in Compose.
2. The Surface container
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
)Surfaceis a Material3 container for UI elementsmodifier.fillMaxSize()makes it fill the whole parentcolorsets the background color
Surfaceis the root container of the Compose UI.
3. The Box container and alignment
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
)Boxis one of the most flexible containers in Compose- it can hold one or multiple children
- it supports overlapping layouts
contentAlignment = Alignment.Centercenters the content
Box + contentAlignmentmakes centered layout very easy.
4. Button layout and Modifier
Button(
onClick = onRequestPermission,
modifier = Modifier
.width(200.dp)
.height(60.dp)
)
{
Text("请求相机权限")
}Key points
onClickis the button click callbackModifier.width / heightgives the button a fixed sizeModifiercan be chained, such as.width().height().padding()
5. Full NoPermissionView example
@Composable
fun NoPermissionView(onRequestPermission: () -> Unit) {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Button(
onClick = onRequestPermission,
modifier = Modifier
.width(200.dp)
.height(60.dp)
) {
Text("请求相机权限")
}
}
}Summary
Box: centers the parent containerButton: fixed sizeText: button label
Now the button no longer fills the whole screen. It stays centered at a fixed size.
6. Key takeaways
Surfaceis the root containerBox + contentAlignment = Alignment.CenterModifiercontrols size and position flexibly- In Compose, the parent controls layout, while children refine it through
Modifier
