android-compose-patterns
Use when building native Android with Jetpack Compose - stateless composables, state hoisting, ViewModel-owned state, edge-to-edge, predictive back, adaptive layout, atomic components, and Material theming over hardcoded values
- License 许可
- Apache-2.0
- 最近更新
- 2026-11-15
- Stars
- ★ 122
- Forks
- 18
01 前言 Front Matter
- name
- android-compose-patterns
- source
- android/skills (Apache-2.0), skydoves/android-testing-skills (Apache-2.0), adapted
- category
- architecture
- tech_stack
- Kotlin
- description
- Use when building native Android with Jetpack Compose - stateless composables, state hoisting, ViewModel-owned state, edge-to-edge, predictive back, adaptive layout, atomic components, and Material theming over hardcoded values
03 SKILL.md 正文
Jetpack Compose Patterns
Overview
Native Android (Jetpack Compose) is chosen when a task needs deep Android integration or the app is already native (see native-vs-flutter-decision). Same discipline as Flutter/SwiftUI: small stateless composables, state hoisted out, reusable atomic components.
Core principle: Composables are stateless functions of state. State is hoisted to a ViewModel; composables emit events upward.
Rules
- Stateless composables + state hoisting. A composable takes its state as parameters and exposes callbacks (
onXxx) — it does not own app state. The screen-level composable connects aViewModelto the stateless UI. ViewModelowns state and logic, exposed asStateFlow/UiState; the composable collects it withcollectAsStateWithLifecycle(). Networking/business rules live in the ViewModel + repository, never in the composable.- Model UI state as a sealed hierarchy:
Loading | Data | Empty | Error—whenover it renders every branch. No happy-path-only screens. - Atomic components: shared library of reusable composables (atoms → molecules → organisms). Reuse before building; grep before adding.
- Material theme, not hardcoded values:
MaterialTheme.colorScheme/typography/ a spacing tokens object (MaterialTheme.spacing, seemobile-design-system-foundation) — never scatteredColor(0xFF...)and magicdp. Support dark theme + dynamic color. remember/derivedStateOfto avoid recomputation; hoistremembered state only when it's genuinely local (scroll, text field).@Previewreusable composables in their key states, and across the matrix (see below).
Edge-to-edge (enforced from targetSdk 35)
- Call
enableEdgeToEdge()beforesetContentin the activity — the opt-out is gone at targetSdk 35+. - Consume insets at the
Scaffold: use itsinnerPaddingandModifier.consumeWindowInsets(innerPadding)on the content so a nested scrollable doesn't double-apply it. - IME padding: apply
Modifier.imePadding()once, at the container that should move with the keyboard — applying it a second time further down the tree produces extra empty space. android:windowSoftInputMode="adjustResize"in the manifest for screens with text input.NavigationSuiteScaffolddoes not automatically propagate its padding to the content slot — apply insets explicitly inside it, don't assume it's handled.
Predictive back (default at targetSdk 36)
onBackPressed()/OnBackPressedCallbackwithoutisEnabledtoggling is not called the same way once predictive back is the default — useBackHandler(simple) orPredictiveBackHandler(custom transition) in Compose, or Navigation 3's built-in handling.- Verify back navigation in this run rather than assuming the old override still fires.
Adaptive layout
currentWindowAdaptiveInfo().windowSizeClassto branch layout by available width/height — never byConfiguration.orientationor a hardcoded device check.NavigationSuiteScaffoldswitches a bottom nav bar to a nav rail automatically at the window-size-class breakpoint — prefer it over hand-rolling the switch.GridCells.Adaptive(minWidth)for grids that should reflow by available width.- Android 16 (opt-out via
PROPERTY_COMPAT_ALLOW_RESTRICTED_RESIZABILITY) and Android 17/API 37 (no opt-out) ignorescreenOrientation/resizeableActivityrestrictions on screens ≥600dp — design every screen to work in both orientations and at tablet width; don't rely on an orientation lock to avoid building the wider layout.
Previews and tests across the matrix
@PreviewScreenSizes,@PreviewFontScale,@PreviewLightDark, or a custom multi-preview withDevices.PHONE/Devices.TABLET— seemobile-visual-self-reviewfor the full size/text-scale/dark matrix.DeviceConfigurationOverride(ForcedSize(...) then FontScale(...) then DarkMode(...))for instrumented matrix tests.rule.enableAccessibilityChecks()on an API 34+ device/emulator before UI-mutating test actions (inconclusive on Robolectric — say so if that's all you ran); seemobile-accessibility.- "Run screenshot tests but do not update reference images" to "fix" a failure — a changed golden is a visual regression until a human confirms it's intended.
Semantics
contentDescriptionon everyImage/Iconthat carries meaning;nullexplicitly for a purely decorative one.Modifier.semantics(mergeDescendants = true)on a composite row so a screen reader announces it once.- Touch targets ≥48dp —
Modifier.size/minimumInteractiveComponentSize().
Worked Example
// ViewModel owns state + logic (unit-testable, no Compose)
class TaskListViewModel(private val repo: TaskRepository) : ViewModel() {
private val _state = MutableStateFlow<UiState<List<Task>>>(UiState.Loading)
val state: StateFlow<UiState<List<Task>>> = _state
fun load() = viewModelScope.launch {
_state.value = UiState.Loading
_state.value = try {
val items = repo.list()
if (items.isEmpty()) UiState.Empty else UiState.Data(items)
} catch (e: CancellationException) {
throw e // never swallow cancellation
} catch (e: Exception) {
UiState.Error(e)
}
}
}
// stateless composable renders state, emits events
@Composable
fun TaskListScreen(state: UiState<List<Task>>, onRetry: () -> Unit) = when (state) {
is UiState.Loading -> AppSpinner()
is UiState.Error -> AppErrorView(message = state.cause.message, onRetry = onRetry)
is UiState.Data -> TaskList(tasks = state.value)
is UiState.Empty -> EmptyView()
}
The fix from the previous version: runCatching { } wrapped around a suspend call inside viewModelScope.launch catches CancellationException along with real errors, which breaks structured concurrency (a cancelled screen keeps "loading" instead of stopping) — use try/catch and rethrow CancellationException explicitly. The Empty branch is now actually emitted when the list comes back empty, not just declared and never reached.
Testing
- Unit-test the
ViewModelwith a fake/mockk repository and a test dispatcher — no Compose. - Compose UI tests (
createComposeRule) assert visible behavior and clicks. Test-first.
Common Mistakes
- A composable holding app state or calling the repository.
- Business logic in the composable instead of the ViewModel.
- Hardcoded colors/dp instead of
MaterialTheme+ tokens. - Collecting flows without
collectAsStateWithLifecycle(leaks/waste). - Only the data branch rendered —
Emptydeclared but never emitted. runCatchingaround a suspend call, swallowingCancellationException.- Assuming edge-to-edge/predictive back still behave like targetSdk <35/<36 after a target bump.
Red Flags
- A
@Composablethat imports a repository or Retrofit service. Color(0xFF...)/magicdpoutside the theme.- No error/empty branch in the
when. enableEdgeToEdge()missing from a new or recently targetSdk-bumped activity.- A screen that only renders correctly in one orientation.
04 同仓库更多 Skills
visual-craft
暂无简介
ux-copy
Use when you write any words a user reads in a mockup or a hand-off - content language and voice, buttons, labels, errors, empty states, confirmations, numbers and dates, and the longest-string check
screen-mockup-html
Use when you draw screens as the design task's HTML mockup - ONE canvas document holding every screen and every variant side by side, the sanitizer-safe recipe, phone and wide frames, the states grid, static control states, and the loopback self-check with screenshots at 375, 768 and 1440 attached to the task
performance-awareness
How the performance score moves for your role. Use when the score context shows a declining trend, or before handing off work you have not self-checked against every criterion.
design-variants
Use when a screen design needs variants - how many, variants as side-by-side rows on the one canvas, what makes two variants genuinely different, recommending one, how the human's choice is read, and narrowing to the chosen one in revision
design-system-authoring
Use when you derive, change or extend a design system - where tokens live per stack, the DTCG token tree, role-based names for both themes, base vs layer vs drift, the DESIGN.md section order, the inventory format, the contrast check and the lint every proposal returns