Step 4 of 15
@Composable functions, Text/Button/Image, Column/Row/Box, modifier chains
Composable functions, modifiers — อิฐก่อนสร้าง UI ด้วย Compose
A composable is a function annotated with @Composable. It describes a piece of UI. Compose reads these functions and renders the screen.
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
@Composable
fun Greeting(name: String) {
Text(text = "Hello, $name!")
}
Call it like a normal function from another composable:
@Composable
fun Screen() {
Greeting(name = "Ada") // renders: Hello, Ada!
}
| Composable | Purpose |
|---|---|
Column | Stack children vertically |
Row | Stack children horizontally |
Box | Stack children on top of each other |
Text | Display text |
Button | Tappable button |
Image | Show an image |
A Modifier changes how a composable looks and behaves. Chain modifiers in order — order matters.
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.clickable
import androidx.compose.material3.Text
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
@Composable
fun StyledBox() {
Box(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
.background(Color.LightGray)
) {
Text(
text = "Tap me",
modifier = Modifier
.padding(8.dp)
.clickable { /* handle tap */ }
)
}
}
Rendered result: a light gray box that fills the width, with 16dp outer padding, and the text "Tap me" inside with 8dp padding and a click action.
Build a profile card step by step.
Step 1 — a reusable avatar:
@Composable
fun Avatar(name: String) {
Box(
modifier = Modifier
.size(56.dp)
.background(Color(0xFF6650A4)),
contentAlignment = androidx.compose.ui.Alignment.Center
) {
Text(text = name.first().toString(), color = Color.White)
}
}
Step 2 — the card using Row:
@Composable
fun ProfileCard(name: String, role: String) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
verticalAlignment = androidx.compose.ui.Alignment.CenterVertically
) {
Avatar(name = name)
Spacer(modifier = Modifier.width(12.dp))
Column {
Text(text = name) // bold name
Text(text = role) // role below
}
}
}
Step 3 — preview it:
@Composable
fun ProfileScreen() {
Column {
ProfileCard(name = "Ada Lovelace", role = "Engineer")
ProfileCard(name = "Alan Turing", role = "Researcher")
}
}
// Rendered layout:
// [A] Ada Lovelace
// Engineer
// [A] Alan Turing
// Researcher
Modifiers apply in the order you chain them.
// padding INSIDE the background
Modifier.background(Color.Red).padding(16.dp)
// padding OUTSIDE the background
Modifier.padding(16.dp).background(Color.Red)
The first puts padding inside the red area. The second puts the red area inside padding. Pick the one that matches your design.
Build a ContactRow composable that shows a circular avatar, a name, and a phone number in a Row. Add clickable so tapping it prints the name to the console. Stack three rows inside a Column and run the preview.