Native foundations

Jetpack Compose explained

Learn Compose through small Kotlin examples covering composables, state ownership, layouts and Material 3.

Apirex TeamUpdated
On this page
  1. What Compose is
  2. Composables
  3. State
  4. Layouts
  5. Material 3
  6. Frequently asked questions

What Compose is

Jetpack Compose is Android’s declarative UI toolkit: you describe a screen in Kotlin as a function of its state. When observed state changes, Compose can run the relevant functions again to update the interface, a process called recomposition.

Compose is a UI toolkit, not a backend or a substitute for application architecture. You still decide where records live, how authentication works and how a screen handles failed requests. Start with explicit local state before connecting an interface to storage and networking.

Create an Android Studio Empty Activity project with Compose enabled. Keep the generated activity and package declaration, then add these functions to a Kotlin file in that package. The shared imports below cover the tutorial’s UI snippets; the generated activity already includes the Android activity and setContent imports.

kotlin
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

As of November 2026, Google’s November release announcement specifies Compose BOM 2026.11.01 and requires Kotlin 2.2 or newer and compileSdk 37.1. Use a compatible current project template and Android Gradle Plugin rather than inserting this version into an old project without checking its toolchain.

The following app-module build.gradle.kts fragment declares the Compose libraries used here. The BOM aligns their versions; it does not add libraries automatically or configure the compiler. Keep the template’s activity-compose dependency and Kotlin Compose plugin, because compiler setup and non-Compose dependencies are separate from BOM version alignment.

kotlin
dependencies {
    val composeBom = platform("androidx.compose:compose-bom:2026.11.01")
    implementation(composeBom)
    implementation("androidx.compose.ui:ui")
    implementation("androidx.compose.foundation:foundation")
    implementation("androidx.compose.material3:material3")
}

Build the unchanged template first, then add one example at a time. For unresolved symbols, distinguish missing imports from missing libraries or incompatible tooling. Read the first meaningful build error before changing versions; random dependency changes can obscure a simple setup problem.

Composables

A composable is a Kotlin function annotated with @Composable that participates in describing UI. It can accept ordinary parameters, allowing one interface component to display different data without owning that data.

kotlin
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
    Text(
        text = "Hello, $name",
        modifier = modifier.padding(16.dp),
        style = MaterialTheme.typography.headlineSmall
    )
}

Call Greeting from the generated activity’s setContent block, wrapped in MaterialTheme. The modifier parameter lets callers control sizing and placement without changing the component’s content. A default Modifier keeps simple calls short while preserving flexibility when the greeting joins a larger screen.

kotlin
// Inside the generated activity's onCreate, after super.onCreate:
setContent {
    MaterialTheme {
        Greeting(name = "Ada")
    }
}

A composable call does not permanently create an object that you later update by finding it on screen. Compose may execute the function again when inputs change, and it can skip work when appropriate. Keep functions focused on describing UI rather than assuming each one runs exactly once.

Do not begin a network request, write a database row or read a large file directly in a composable body. Recomposition could repeat that work. Put operations in an appropriate state holder or use an effect API with deliberate keys; these examples stay local so the update behavior is clear.

Extract components around meaningful responsibilities such as an action row, labeled value or empty state. Avoid creating a new abstraction for every line solely to shorten the parent function. Clear inputs and a small purpose make a component easier to preview, test and reuse.

State

State is data that changes what the interface displays, and Compose needs observable state to react to it. For a local integer, remember with mutableIntStateOf retains an observable value across recompositions while the composable remains in composition.

kotlin
@Composable
fun Counter() {
    var count by remember { mutableIntStateOf(0) }
    Column(modifier = Modifier.padding(16.dp)) {
        Text("Count: $count")
        Button(onClick = { count++ }) {
            Text("Add one")
        }
    }
}

The delegated property syntax uses the runtime getValue and setValue imports included by the shared runtime import. Tapping the button changes count, and the text reads that updated state. A plain local integer initialized each time the function runs would not provide equivalent retained, observable behavior.

Remember is not durable storage. By itself it does not preserve values across activity recreation, process death or removal from composition. Consider rememberSaveable for supported small UI values, an appropriate state holder for shared screen state, and persistent storage for important user records.

State hoisting moves ownership upward and passes values and events downward. The child displays the current value without deciding where it is stored. This is useful when several controls share a value, a parent applies validation, or a test needs to supply predictable data.

kotlin
@Composable
fun CounterRoute() {
    var count by remember { mutableIntStateOf(0) }
    CounterContent(count = count, onIncrement = { count++ })
}

@Composable
fun CounterContent(count: Int, onIncrement: () -> Unit) {
    Row(
        modifier = Modifier.padding(16.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text("Count: $count", modifier = Modifier.weight(1f))
        Button(onClick = onIncrement) { Text("Add one") }
    }
}

Keep one authoritative owner rather than copying the same value into several remembered variables. Copies can drift apart when only one is updated. Pass values down and callbacks up, leaving the owner to decide whether an event changes local state or starts work outside composition.

Remember can also cache a calculation, but its keys must include changing inputs that affect the result. Remembering a sorted list without its input key can produce stale content. For genuinely expensive processing, prefer preparing display data outside composition rather than merely hiding repeated work behind a cache.

Layouts

Column places children vertically, Row horizontally, and Box layers or aligns content inside one region. LazyColumn is a scrolling list that composes items as needed, making it useful for longer collections.

The next example combines all four containers and gives rows stable keys. Keys must be unique and remain associated with the same logical item as the list changes. Avoid using the current index for reorderable records because inserting one item would change the identity of subsequent rows.

kotlin
data class Task(val id: Long, val title: String)

@Composable
fun TaskList(tasks: List<Task>) {
    Column(modifier = Modifier.fillMaxSize().padding(16.dp)) {
        Row(modifier = Modifier.fillMaxWidth()) {
            Text("Tasks", modifier = Modifier.weight(1f))
            Text("${tasks.size}")
        }
        Box(modifier = Modifier.fillMaxWidth().weight(1f)) {
            if (tasks.isEmpty()) {
                Text("Nothing here yet", Modifier.align(Alignment.Center))
            } else {
                LazyColumn(modifier = Modifier.fillMaxSize()) {
                    items(tasks, key = { it.id }) { task ->
                        Text(task.title, Modifier.fillMaxWidth().padding(12.dp))
                    }
                }
            }
        }
    }
}

Call TaskList(listOf(Task(1L, "Read"), Task(2L, "Walk"))) inside MaterialTheme. The Column fills the available space, the header Row distributes horizontal space, and the Box takes the remaining height. The empty-state label is centered without changing the parent layout or introducing a second scrolling container.

Modifier is an ordered chain for sizing, spacing, drawing and interaction. Padding adds space, fillMaxWidth requests available width, and weight distributes remaining space in a Row or Column. Some modifiers depend on their layout scope, so moving a weighted child into another container requires reconsidering its constraints.

Order matters: padding before a background changes the painted region compared with padding after it, and clickable placement changes the touch region. If the result is confusing, simplify the chain and inspect one operation at a time. Fixed dimensions that happen to fit one phone can conceal rather than solve a layout problem.

For performance, use stable keys, remember reusable calculations with correct inputs and avoid heavy work in composition. Lazy lists do not make large image decoding free. Measure scrolling on representative devices and optimize demonstrated bottlenecks rather than adding caching to every small function.

Material 3

Material 3 provides themed components such as Button, TopAppBar and Scaffold. MaterialTheme supplies color, typography and shape values so components can follow one shared design system.

kotlin
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DemoScreen() {
    MaterialTheme {
        Scaffold(
            topBar = { TopAppBar(title = { Text("Counter") }) }
        ) { innerPadding ->
            Column(modifier = Modifier.padding(innerPadding)) {
                Greeting(name = "Ada")
                Counter()
            }
        }
    }
}

Run DemoScreen() from setContent for the complete screen. Scaffold provides inner padding accounting for its bars; applying it prevents content from sitting underneath the top bar. The opt-in supports Material 3 configurations where the app-bar API requires it, and Counter supplies the interactive Button.

Dynamic color is optional on Android 12 and later. An app can select dynamicLightColorScheme or dynamicDarkColorScheme behind a suitable version check and use a normal light or dark scheme on older devices. MaterialTheme alone does not automatically enable wallpaper-derived colors.

Before adding brand styling, test dark appearance, larger text and empty content. Theme tokens encourage consistency but do not guarantee sufficient contrast for custom colors or usable layouts at every text size. Keep action labels meaningful and verify the complete interaction using accessibility services.

Apirex generates Kotlin/Compose projects you can open in Android Studio and Swift/SwiftUI projects you can open in Xcode. Android and Apple implementations are separate projects. Review generated state ownership, list identity and error handling just as you would hand-written code; a successful build is only the start of testing.

Try the state-hoisted component with a fixed value and an empty callback before wiring it to changing state. You should see the supplied number, but tapping should do nothing. This exercise demonstrates the contract clearly: the child reports an event, and only its owner decides whether that event changes the value.

Next, add a reset action in the owner and pass another callback to the child. Avoid allowing the child to reach directly into the parent’s storage. Keeping state transitions visible makes it easier to add a limit, validation message or analytics event without giving a small presentation component unrelated responsibilities.

Practice the list with an empty collection, a single item and many items with long titles. Then insert a task at the beginning and confirm the remaining records retain their identities. These checks expose layout and key assumptions that a short static sample can conceal, especially when row-local state is added later.

When you connect real data, represent loading, content and failure explicitly rather than treating an empty list as all three. A user should be able to tell whether there are no tasks, the app is still fetching them or the request failed. Compose renders these states, but the application must define their meaning.

Use the smallest useful experiment when debugging. If a button does not appear to update the screen, first verify its callback runs and that the displayed value reads observable state. Investigate persistence and backend behavior only after the local state transition is understood; otherwise multiple independent problems can look like one rendering defect.

Frequently asked questions

Do I need XML layouts?

No. Compose describes UI in Kotlin. Existing View-based screens can coexist with Compose during gradual adoption.

Why does my counter reset after rotation?

Remember does not by itself survive activity recreation. Use saveable state or an appropriate longer-lived owner according to the requirement.

Does the BOM install every library?

No. It aligns versions for libraries you explicitly declare. Compiler setup and non-Compose dependencies remain separate.

Why do stable keys matter?

They associate item state with logical records rather than changing positions. Use unique stable identifiers for mutable lists.

Can I paste the Gradle block into any project?

No. It is a dependency fragment for a compatible Compose-enabled Android project. Check the dated release requirements before upgrading.

All guides

Build it on your own computer

Describe the app and Apirex writes real source you own, then builds it on your machine.

AndroidKotlin · Jetpack ComposeReal source on your computer

Opens Apirex with this prompt. Pick the Android · Kotlin tab before you send. The Free plan includes 5 Rex Credits a day.