Adaptive
Android (Google)OfficialCreated by Google LLCDistributed by Android (Google)
- Skill
- Workflow
- Software development
- Apache-2.0
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a structured workflow for making Android applications responsive across diverse form factors, including phones, tablets, foldables, desktops, and more. It covers implementing adaptive navigation, multi-pane layouts with Navigation 3, responsive list configurations, and state preservation across configuration changes. The guide emphasizes using modern Compose APIs like MediaQuery, Grid, and FlexBox to ensure a seamless user experience regardless of device capabilities or input methods.
What it does
- Provides a step-by-step workflow for migrating existing Android apps to be fully adaptive.
- Explains how to implement adaptive navigation bars and rails using NavigationSuiteScaffold.
- Guides the creation of multi-pane layouts using Navigation 3 Scene strategies.
- Details how to make lists and grids responsive using adaptive sizing and layout APIs.
- Offers best practices for preserving UI and media playback state during configuration changes.
- Includes instructions for enhancing desktop experiences with keyboard shortcuts and custom cursors.
When to use it
- When you need to update an existing Android app to support multiple screen sizes and form factors.
- When building a new app that must run on phones, tablets, foldables, and desktop environments.
- When you need to fix state loss issues occurring during device rotation or folding.
- When implementing complex multi-pane navigation patterns in a Compose-based application.
Advantages
- Promotes a consistent user experience across the entire Android ecosystem.
- Leverages modern, recommended Jetpack Compose APIs for layout and navigation.
- Provides robust strategies for state management that prevent common bugs.
- Includes specific guidance for challenging form factors like foldables and desktop.
Usage examples
- “How do I make my existing phone-only app work well on tablets and foldables?”
- The agent will guide you through the adaptive workflow, starting with UI verification, migrating to adaptive navigation, and implementing multi-pane layouts.
- “My video player resets every time I rotate the device. How do I fix this?”
- The agent will provide instructions on using rememberSaveable and specific ExoPlayer listener patterns to preserve playback state across configuration changes.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/android/adaptive/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip adaptive.zip -d .agents/skills
Documentation by Google LLC
Prerequisites
The app must:
Use Compose for all screens. If it's still using Fragments or Views, suggest using the XML to Compose skill to migrate those screens.
Use Jetpack Navigation 3. If it doesn't, suggest the Navigation 3 skill to migrate the app.
Workflow to make an app adaptive
To make an app adaptive, follow these steps or a subset of them adapting to the task.
Step 1: Verify current UI
Step 2: Make the navigation bar adaptive
Step 3: Add multi-pane layouts
Step 4: Make vertical lists adaptive by changing the number of columns
Step 5: Hide app bars when scrolling
Step 6: Preserve UI state across configuration changes
Step 7: Add desktop experiences
Step 8: Support foldable devices
Step 1. Verify current UI
Ensure that screenshot tests exist to verify the current UI on different form factors. If they don't exist, add the Compose Preview Screenshot Testing tool. Use the following annotation to create previews for all the major form factors. For example:
@Preview(name = "Phone", device = Devices.PHONE, showBackground = true)
@Preview(name = "Foldable", device = Devices.FOLDABLE, showBackground = true)
@Preview(name = "Tablet", device = Devices.TABLET, showBackground = true)
@Preview(name = "Desktop", device = Devices.DESKTOP, showBackground = true)
annotation class FormFactorPreviews
@PreviewTest
@FormFactorPreviews
@Composable
fun FeedScreenPreview() {
SnippetsTheme {
Box {
Text("My Screen")
}
}
}<br />
Step 2. Make the navigation bar adaptive
Bottom navigation bars are optimized for touch input when the user is holding a phone in portrait mode. On larger screen hand-held devices, like tablets and unfolded foldables, the navigation area must be accessible from the edge of the screen (navigation rail).
If you need to provide more screen space for the content, hide the navigation area. Examples of this include:
Hiding the navigation bar when the user scrolls down and showing it again when the user scrolls up. The assumption is that when the user is scrolling down, they are consuming content but when scrolling up they are trying to navigate away from that content.
Hiding the navigation area when its content is distracting. For example, in camera previews or when displaying a full-screen photo.
When the detail screen is displayed full-screen on mobile, full-screen mode must be deactivated on larger screens.
Steps to migrate:
Locate the existing navigation bar.
Convert each item to a
NavigationSuiteItem.Identify whether the navigation bar's visibility changes. For example, if it is wrapped with an
AnimatedContentorAnimatedVisibilitycomposable. If so, follow the guidance in the "Control navigation area visibility".Replace the container that held the navigation bar (often a
Scaffold) withNavigationSuiteScaffoldfrom the Material 3 adaptive layouts library.Supply the navigation items using the
navigationItemsparameter ofNavigationSuiteScaffold.
Step 2.1. Control navigation area visibility
If the navigation bar's visibility changes - it is hidden under certain
scenarios or on certain screens - this behavior must be maintained with the
adaptive navigation area. This is done using NavigationSuiteScaffold's state
parameter.
Steps to migrate:
Identify the scenarios under which the navigation bar is hidden. This is usually done with a boolean variable for the visibility. Use
isNavBarVisibleorshouldShowNavBaras the variable name.Create an instance of
NavigationSuiteScaffoldStateusingrememberNavigationSuiteScaffoldState()and pass it toNavigationSuiteScaffold.When the navigation area visibility changes, use a
LaunchedEffectto callshoworhideon theNavigationSuiteScaffoldState.
For example:
// Pass this variable to any composable that needs to control the navigation area visibility
var isNavBarVisible by remember { mutableStateOf(true) }
val scaffoldVisibilityState = rememberNavigationSuiteScaffoldState()
NavigationSuiteScaffold(
navigationSuiteItems = navItems,
state = scaffoldVisibilityState
) {
// Main content
}
LaunchedEffect(isNavBarVisible){
if (isNavBarVisible) {
scaffoldVisibilityState.show()
} else {
scaffoldVisibilityState.hide()
}
}<br />
Step 3. Add multi-pane layouts using Navigation 3 Scenes
Analyze the codebase looking for related screens - tapping on something in one screen opens another screen that shows information related to the first. There are two canonical screen relationships: list-detail and supporting pane.
IMPORTANT: You must use the Navigation 3 SceneStrategy approach to implement
multi-pane layouts. Do not use ListDetailPaneScaffold or
SupportingPaneScaffold.
Step 3.1. List-detail
Identify the list and detail screens
List-detail layouts display a list of items (this is the list screen) and clicking on an item opens a new screen that shows more details about that item (the detail screen).
Typical usage includes productivity apps like email, notes, and messaging.
Unless requested explicitly, avoid this pattern when the detail content requires substantial screen space (e.g., images or media that benefits from a full-screen presentation).
Add a Material list-detail SceneStrategy
Add the
androidx.compose.material3.adaptive:adaptive-navigation3libraryCreate an
androidx.compose.material3.adaptive.navigation3.ListDetailSceneStrategyusingrememberListDetailSceneStrategyPass the
ListDetailSceneStrategytoNavDisplayusing itssceneStrategiesparameter
Use metadata to identify the list and detail screens
Add metadata using
entry(metadata = ...)orNavEntry(metadata = ...)to the list entry usingListDetailSceneStrategy.listPane(detailPlaceholder = { <placeholder composable> }).Use the
detailPlaceholderparameter to add a placeholder on the detail screen when no list items are selected.Add metadata to the detail entry using
ListDetailSceneStrategy.detailPane().
Important considerations
When a detail screen displays its content full-screen on mobile (content fills the entire screen, bars or rails are hidden), full-screen mode must be deactivated if it's part of a list-detail layout.
Detail screens must not show a back arrow when on a list-detail layout.
For a reference implementation, check the Nav3 Material List Detail recipe.
Step 3.2. Supporting pane
Identify supporting pane screens where a main screen displays a single item, and selecting it opens a "supporting screen" with more details. The supporting screen complements the main screen and is shown in a supporting pane.
Add a Material supporting pane SceneStrategy
If you haven't already, add the
androidx.compose.material3.adaptive:adaptive-navigation3libraryCreate an
androidx.compose.material3.adaptive.navigation3.SupportingPaneSceneStrategyusingrememberSupportingPaneSceneStrategyPass the
SupportingPaneSceneStrategytoNavDisplayusing itssceneStrategiesparameter
Use metadata to identify the main and supporting screens
Add metadata using
entry(metadata = ...)orNavEntry(metadata = ...)to the main entry usingSupportingPaneSceneStrategy.mainPane()Add metadata to the supporting entry using
SupportingPaneSceneStrategy.supportingPane()
Step 3.3. Run screenshot tests
If you have made changes, record new reference files. Ask the user to visually verify that the new layouts are correct.
Step 4. Make vertical lists adaptive by changing the number of columns
Step 4.1. Make lazy lists adaptive
Look for the following vertical list composables: LazyColumn,
LazyVerticalGrid, LazyVerticalStaggeredGrid.
Steps to migrate:
Choose a suitable minimum width in dp for the column. The item must be clearly visible to the user at this width.
For
LazyColumn: change to aLazyVerticalGridand follow the instruction laterFor
LazyVerticalGrid: change thecolumnsparameter to useGridCells.Adaptive(<width>.dp)For
LazyVerticalStaggeredGrid: change thecolumnsparameter to useStaggeredGridCells.Adaptive(<width>.dp)
Step 4.2. Migrate non-lazy lists to Grid
WARNING: Grid is an experimental API available from Compose 1.11.0-beta01. Confirm with the user that they are happy to use an experimental API in their codebase.
Look for any Column that contains multiple items of the same type and replace
it with Grid. Do not replace it with LazyVerticalGrid or any other lazy
layout. Do not place Grid inside the existing Column. Completely replace it.
Grid is configured by supplying a lambda (an extension function on
GridConfigurationScope) to its config parameter. Inside the lambda,
constraints provides the minimum and maximum dimensions of the grid container
and can be used to change the number of rows and columns based on the available
size. For example, the following code configures Grid such that when the
available width is:
less than 800dp, a 2x4 grid is used
800dp or more, a 4x2 grid is used
Grid(
config = {
val maxWidthDp = constraints.maxWidth.toDp()
val (cols, rows) = if (maxWidthDp < 800.dp){
2 to 4
} else{
4 to 2
}
val gapSizeDp = 8.dp
val cellSize = ((maxWidthDp - (gapSizeDp * (cols - 1))) / cols).coerceAtLeast(0.dp)
repeat(cols) { column(cellSize) }
repeat(rows) { row(cellSize) }
gap(gapSizeDp)
}
) { /** items **/ }<br />
Grid is an experimental API so add the @OptIn(ExperimentalGridApi::class)
annotation to any function that uses it.
Step 5: Hide App Bars when scrolling
In an app with multiple top-level destinations, each screen must manage its own app bar state independently. There are two main scroll behaviors:
exitUntilCollapsedScrollBehavior: Hides on scroll down, stays hidden while you scroll up until you reach the very top (0 offset).enterAlwaysScrollBehavior: Hides on scroll down, shows immediately on scroll up.
Step 6: Preserve UI state across configuration changes
IMPORTANT: Never add android:configChanges or android:screenOrientation
to AndroidManifest.xml to suppress Activity recreation or lock orientation.
Opting out of recreation hides state-loss bugs instead of fixing them, breaks
adaptive resource reloading, and prevents an app's process from restarting.
When fixing state loss across configuration changes, systematically audit
every usage of remember across all screens, components, and state holders
(in other words, do not only search for remember { mutableStateOf(...) }):
Step 6.1. Preserve primitive and custom UI state in Composables
Replace
remember { mutableStateOf(...) }withrememberSaveable { mutableStateOf(...) }for user input and interactive UI state, such asTextFielddraft text, search queries, scroll position, and toggle states.Key state on relevant identifiers when appropriate (e.g.,
rememberSaveable(conversationId) { mutableStateOf("") }).For custom data classes or collections (for example, a
Set) that are not nativelyBundle-saveable:When delegating a
MutableState<T>viavar state by rememberSaveable(...) { mutableStateOf(...) }, pass your customSaverusingstateSaver(do not passsaver = ...when the block returnsMutableState<T>):
// this Saver implementation converts CustomState object which we don't know how to save
// to List<String> which we can save
private val CustomStateSaver = Saver<CustomState, List<String>>(
save = { customState -> customState.values.map { it.value } },
restore = { values -> CustomState(values.map { CustomStateValue.valueOf(it) }.toSet()) }
)
@Composable
fun MyComposable() {
var customState by rememberSaveable(stateSaver = CustomStateSaver) {
mutableStateOf(CustomState())
}
}<br />
Alternatively, annotate the class with
@Serializableand userememberSerializable.
Step 6.2. Preserve scroll state in lazy and scrollable layouts
Plain remember { LazyListState() }, remember { LazyGridState() }, and
remember { ScrollState(...) } do not save scroll position across
configuration changes because they bypass the state class's Saver.
Inspect all scrollable containers (LazyColumn, LazyRow, LazyVerticalGrid,
LazyHorizontalGrid, LazyVerticalStaggeredGrid, Modifier.verticalScroll,
and Modifier.horizontalScroll) across all screens and reusable components, and
replace plain remember instantiations with the built-in saveable factory
functions:
remember { LazyListState() }->rememberLazyListState()remember { LazyGridState() }->rememberLazyGridState()remember { LazyStaggeredGridState() }->rememberLazyStaggeredGridState()remember { ScrollState(initial = 0) }->rememberScrollState()
Step 6.3. Preserve Navigation 3 state and multiple back stacks
Check out the Navigation 3 guide to Save and manage navigation state for details.
Step 6.4. Preserve media playback state (ExoPlayer / Media3)
When an MediaPlayer (such as ExoPlayer) is created inside a composable with remember, it is
released on disposal and recreated from scratch on configuration change,
resetting playback to 0:00 and auto-playing even if the user had paused the
video.
To preserve ExoPlayer playback state (currentPosition and playWhenReady):
Store
savedPositionMs(mutableLongStateOf(0L)) andsavedPlayWhenReady(mutableStateOf(true)) usingrememberSaveable(videoResId).Keep saved state updated during playback --- do not only save in
onDispose: updatesavedPlayWhenReadyandsavedPositionMsin aPlayer.Listener(onPlayWhenReadyChanged,onPositionDiscontinuity) and periodically inside aLaunchedEffect(player)loop while active.Initialize the player with the restored state : Set
playWhenReady = savedPlayWhenReadyand callseekTo(savedPositionMs)beforeprepare().Guard
LifecycleStartEffectso it does not auto-play a paused video or overwritesavedPlayWhenReady:In
LifecycleStartEffect(player), only callplayer.play()whensavedPlayWhenReadyistrue(otherwise a paused video will start playing again after restoration).In
onStopOrDispose, captureval wasPlaying = player.playWhenReadyandsavedPositionMs = player.currentPositionbefore callingplayer.pause(), then restoresavedPlayWhenReady = wasPlayingso thatplayer.pause()on stop/dispose does not overwritesavedPlayWhenReadytofalse:
@UnstableApi
@Composable
private fun rememberExoPlayer(@RawRes videoResId: Int, fromUri: Unit.(Uri) -> MediaItem): ExoPlayer {
val context = LocalContext.current
var savedPositionMs by rememberSaveable(videoResId) { mutableLongStateOf(0L) }
var savedPlayWhenReady by rememberSaveable(videoResId) { mutableStateOf(true) }
val player = remember(videoResId) {
ExoPlayer.Builder(context.applicationContext).build().apply {
setMediaItem(MediaItem.fromUri(RawResourceDataSource.buildRawResourceUri(videoResId)))
repeatMode = Player.REPEAT_MODE_ONE
playWhenReady = savedPlayWhenReady
seekTo(savedPositionMs)
prepare()
}
}
DisposableEffect(player) {
val listener = object : Player.Listener {
override fun onPlayWhenReadyChanged(playWhenReady: Boolean, reason: Int) {
savedPlayWhenReady = playWhenReady
savedPositionMs = player.currentPosition
}
override fun onPositionDiscontinuity(
oldPosition: Player.PositionInfo,
newPosition: Player.PositionInfo,
reason: Int
) {
savedPositionMs = newPosition.positionMs
}
}
player.addListener(listener)
onDispose {
player.removeListener(listener)
player.release()
}
}
LaunchedEffect(player) {
while (isActive) {
savedPositionMs = player.currentPosition
delay(200)
}
}
LifecycleStartEffect(player) {
if (savedPlayWhenReady) {
player.play()
}
onStopOrDispose {
val wasPlaying = player.playWhenReady
savedPositionMs = player.currentPosition
player.pause()
savedPlayWhenReady = wasPlaying
}
}
return player
}<br />
Step 7: Add desktop experiences
Step 7.1: Identify the required desktop feature
Look at the user's prompt, requirements, or uploaded files to determine which desktop feature needs to be implemented.
Step 7.2: Run feature-specific processing
Based on the feature identified, you must read the corresponding reference file and follow its instructions:
Keyboard Shortcuts -> read
references/keyboard_shortcuts.mdTooltips -> read
references/tooltips.mdCustom Cursors -> read
references/custom_cursors.md
Each reference starts by searching the whole app for the targets of that feature. Write that list down first, implement all of it (not only the first screen you open), and re-check the list before you finish.
Step 8. Support foldable devices
Tabletop mode allows users to view and interact with content while their foldable device is placed on a flat surface. The top screen is angled at a convenient viewing angle and provides visual content. The bottom screen is flat on the surface and provides controls for that content.
To support foldable devices, identify any screens that provide the following:
Media and audio playback or streaming: The video or audio content renders on the upright top display. Comments, details, and playback scrubber controls render on the flat bottom surface.
Video calls: Remote participants display on the upright screen. Microphone and camera toggles, participant lists, and chat controls sit on the flat bottom surface.
Camera capture: The camera viewfinder displays on the upright screen. The shutter button, zoom controls, and exposure sliders sit on the flat bottom surface for hands-free photography.
Photo editing: The image canvas displays unobstructed on the upright screen. Sliders, preset palettes, and curves remain accessible on the flat bottom surface.
Audio mixing: Waveforms and stem controls display on the upright screen. Turntable decks and pads sit on the flat bottom surface.
Cooking: Viewing recipe instructions hands-free on the upright screen while keeping timers or step navigation on the bottom screen.
Slide shows: Viewing presentation slides on the top screen with presenter notes or navigation on the bottom screen.
To create layouts for foldables on these screens, you must read tabletop posture.
Final step: Build and test
Build the app and run the local tests. If the project has screenshot tests, run them but DO NOT update the reference images. Prompt the user to do this after they have viewed the screenshot diffs.
Additional documentation for experimental adaptive APIs
The following APIs are available from Compose 1.11.0.
FlexBox
Check the FlexBox documentation:
MediaQuery
Check the MediaQuery documentation when you need to query the device's screen size, pointer precision, keyboard type, whether it has cameras or microphones, and other device capabilities.
Grid
Check the Grid documentation when you need to display a fixed number of items in a grid layout:
Files
- ATTRIBUTION.mdAdded by AutoGineer953 B
- LICENSELicence file added by AutoGineer11.1 KiB
- SKILL.md21.6 KiB
- references/android/develop/ui/compose/layouts/adaptive/flexbox/container-behavior.md9.1 KiB
- references/android/develop/ui/compose/layouts/adaptive/flexbox/get-started.md2.3 KiB
- references/android/develop/ui/compose/layouts/adaptive/flexbox/index.md5.8 KiB
- references/android/develop/ui/compose/layouts/adaptive/flexbox/item-behavior.md8.3 KiB
- references/android/develop/ui/compose/layouts/adaptive/grid/container-properties.md15.8 KiB
- references/android/develop/ui/compose/layouts/adaptive/grid/get-started.md1.8 KiB
- references/android/develop/ui/compose/layouts/adaptive/grid/index.md4.2 KiB
- references/android/develop/ui/compose/layouts/adaptive/grid/item-properties.md5.6 KiB
- references/android/develop/ui/compose/layouts/adaptive/mediaquery/index.md13.8 KiB
- references/android/guide/navigation/navigation-3/recipes/material-listdetail.md6.4 KiB
- references/android/guide/navigation/navigation-3/save-state.md5.9 KiB
- references/android/studio/preview/compose-screenshot-testing-with-testsuites.md7.3 KiB
- references/custom_cursors.md4.2 KiB
- references/foldable-tabletop.md3.8 KiB
- references/keyboard_shortcuts.md6.0 KiB
- references/tooltips.md4.2 KiB
references/android/develop/ui/compose/layouts/adaptive/grid/container-properties.md
You can define a Grid container configuration to create flexible layouts that respond to different screen sizes and content types. This page describes how to do the following:
Define a grid: Set up the basic structure of rows and columns.
Place items in a grid: Understand how items are placed into grid cells and how to change flow direction.
Manage track sizing: Use fixed, percentage, flexible, and intrinsic sizing to set track sizes.
Set gaps: Manage the "gutters" between rows and columns.
Define a grid
A grid consists of columns and rows.
The Grid composable has a config parameter
that accepts a lambda to define the columns and rows
within GridConfigurationScope.
The following example defines a grid that has three rows and two columns,
each with a fixed size specified in Dp:
Grid(
config = {
repeat(2) {
column(160.dp)
}
repeat(3) {
row(90.dp)
}
}
) {
}<br />
Place items in a grid
Grid takes the UI elements
in the content lambda and places them into grid cells.
The grid lays out items regardless of
whether you have explicitly defined the rows and columns.
By default,
Grid tries to place a UI element in the available grid cell in the row;
if it can't, it places it in an available grid cell in the next row.
If there are no empty cells, Grid creates a new row.
In the following example, the grid has six grid cells
and places a card into each one (Figure 1).
Each grid cell is 160dp x 90dp,
making the total grid size 320dp x 270dp.
Grid(
config = {
repeat(2) {
column(160.dp)
}
repeat(3) {
row(90.dp)
}
}
) {
Card1()
Card2()
Card3()
Card4()
Card5()
Card6()
}<br />
Image: Six cards are placed in a grid that has three rows and two columns. Figure 1. Six cards are placed in a grid that has three rows and two columns.
To change this default behavior to filling by column,
set the flow property to GridFlow.Column.
Grid(
config = {
repeat(2) {
column(160.dp)
}
repeat(3) {
row(90.dp)
}
gap(8.dp)
flow = GridFlow.Column // Grid tries to place items to fill the column
},
) {
Card1()
Card2()
Card3()
Card4()
Card5()
Card6()
}<br />
Image: The flow function changes the direction to place items. Figure 2 . GridFlow.Row (left) and GridFlow.Column (right).
Manage track sizing
Rows and columns are collectively referred to as a grid track. You can specify the size of a grid track using one of the following methods:
Fixed (
Dp): Allocates a specific size (e.g.,column(180.dp)).Percentage (
Float): Allocates a percentage of the total available space from0.0fto1.0f(e.g.,row(0.5f)for 50%).Flexible (
Fr): Distributes remaining space proportionally after fixed and percentage tracks are calculated. For example, if two rows are set to1.frand3.fr, the latter receives 75% of the remaining height.Intrinsic : Sizes the track based on the content inside it. For more information, see Determine grid track size intrinsically.
The following example uses the different track sizing options to define the row heights:
Grid(
config = {
column(1f)
row(100.dp)
row(0.2f)
row(1.fr)
row(GridTrackSize.Auto)
},
modifier = Modifier.height(480.dp)
) {
PastelRedCard("Fixed(100.dp)")
PastelGreenCard("Percentage(0.2f)")
PastelBlueCard("Flex(1.fr)")
PastelYellowCard("Auto")
}<br />
Image: Row heights defined using the four primary track sizing options. Figure 3 . Row heights defined using the four primary track sizing options in Grid.
Set the minimum size for flexible grid tracks
When a grid container has no remaining space,
a standard flexible track can shrink to 0.dp.
To prevent this and ensure content isn't crushed,
use GridTrackSize.MinMax
to enforce an explicit minimum size while keeping the track flexible.
The following example allocates at least 100.dp to the first row:
Grid(
config = {
column(1f)
// The first row has a minimum height of 100.dp and can expand to
// the half of the remaining space.
row(GridTrackSize.MinMax(100.dp, 1.fr))
// The second row takes the half of the remaining space.
row(1.fr)
// The third row has a fixed height of 200.dp.
row(200.dp)
},
modifier = Modifier.size(360.dp) // Total grid height is 360.dp
) {
PastelRedCard("MinMax(100.dp, 1.fr)")
PastelGreenCard("Flex(1.fr)")
PastelBlueCard("Fixed(200.dp)")
}<br />
Image: Row heights defined using the four primary track sizing options. Figure 4 . The first row has at least 100.dp height.
Set the minimum grid track size to place lazy lists
Standard flexible tracks automatically query the intrinsic sizes of
their children to establish a base size.
However, Jetpack Compose prohibits querying the intrinsic sizes of
SubcomposeLayout, which backs components,
such as LazyColumn and LazyRow.
Placing a lazy list inside a standard flexible track causes
an IllegalStateException crash.
To safely place lazy lists inside a flexible grid track,
use MinMax with an explicit minimum size (such as 0.dp)
to bypass the intrinsic measurement pass.
Grid(
config = {
column(1f)
// The first row's height is determined by the height of the Text composable.
row(GridTrackSize.Auto)
// The second row occupies the remaining space, allowing the LazyColumn to scroll.
row(GridTrackSize.MinMax(0.dp, 1.fr))
gap(8.dp)
},
modifier = Modifier.size(width = 170.dp, height = 240.dp)
) {
Text("LazyColumn in a Grid")
// The LazyColumn is placed in the second row, filling the remaining space.
LazyColumn(verticalArrangement = Arrangement.spacedBy(4.dp)) {
items(100) { number ->
PastelGreenCard("Card $number")
}
}
}<br />
Image: Row heights defined using the four primary track sizing options. Figure 5 . LazyColumn in a grid cell.
Determine grid track size intrinsically
You can use intrinsic sizing for a Grid
when you want the layout to adapt to the content,
rather than forcing it into a fixed container.
The grid track size is determined with the following values:
GridTrackSize.MaxContent: Use the content's maximum intrinsic size (e.g., the width is determined by the full length of the text in a text block with no wrapping).GridTrackSize.MinContent: Use the content's minimum intrinsic size (e.g., the width is determined by the longest single word in a text block).GridTrackSize.Auto: Use a flexible size for a track that adapts based on available space. It behaves likeMaxContentby default, but shrinks and wraps its content to fit within the parent container.
The following example places two texts side by side. The column size for the first text is determined by the required minimum width to display the text, and the second column width depends on the required maximum width of the text.
Grid(
config = {
column(GridTrackSize.MinContent)
column(GridTrackSize.MaxContent)
row(1.0f)
},
modifier = Modifier.width(480.dp)
) {
Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras imperdiet.")
Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras imperdiet.")
}<br />
Image: Intrinsic sizes specified in the columns. Figure 5. Intrinsic sizes specified in the columns.
Set gaps between rows and columns
Once your grid tracks are sized,
you can modify the grid gap to refine the spacing between the tracks.
You can specify the column gap with the columnGap function,
and the row gap with rowGap. In the following example,
there is a 16dp gap between each row,
and an 8dp gap between each column (Figure 5).
Grid(
config = {
repeat(2) {
column(160.dp)
}
repeat(3) {
row(90.dp)
}
rowGap(16.dp)
columnGap(8.dp)
}
) {
Card1()
Card2()
Card3()
Card4()
Card5()
Card6()
}<br />
Image: Gaps between rows and columns. Figure 6. Gaps between rows and columns.
You can also use the convenience function gap
to define gaps of the same column and row size,
and to define column and gap sizes separately using a single function.
The following code adds 8dp gaps to the grid:
Grid(
config = {
repeat(2) {
column(160.dp)
}
repeat(3) {
row(90.dp)
}
gap(8.dp) // Equivalent to columnGap(8.dp) and rowGap(8.dp)
}
) {
Card1()
Card2()
Card3()
Card4()
Card5()
Card6()
}<br />
Define grid areas with named areas
Named areas allow you to attach names to groups of grid cells, which are called grid areas. You can use these names instead of coordinate indexes when placing UI elements in the grid.
Using named areas has two main benefits to code readability:
When defining the grid layout, the purpose and placement of the expected content is clear.
When adding the content, the purpose of that content is clear.
To organize complex layouts clearly, you can decouple your physical grid structure from child placement by defining semantic grid areas.
Inside the config lambda, use the area function in
GridConfigurationScope to register named areas in the grid.
You can then assign child composables to these areas
using the gridItem modifier
with the corresponding area identifier. The area function maps
a semantic identifier (such as an enum class value or a string key) to
a set of physical grid coordinates. Grid lines and indexes are 1-based
(that is, the first row is 1, and the first column is 1).
For example, you define a grid that has four area IDs:
/**
* An enum representing the IDs for named areas within the grid.
*/
enum class GridAreaNames {
Area1,
Area2,
Area3,
Area4
}<br />
Provide the name for the area using the areaId parameter along with the area's
cell coordinates and spans.
The gridItem modifier uses the areaId as a key
to assign each child item to its designated grid area,
as shown in the following example:
Grid(
config = {
// Define a single column that takes all available width.
repeat(2) { column(0.5f) }
// Define four rows, each taking 25% of the total height.
repeat(4) { row(0.25f) }
// Define named grid areas by associating an areaId with specific row and column indices.
// Row and column indices are 1-based.
area(areaId = GridAreaNames.Area1, row = 1, column = 1, columnSpan = 2)
area(areaId = GridAreaNames.Area2, row = 2, column = 1, rowSpan = 3)
area(areaId = GridAreaNames.Area3, rows = 2..3, columns = 2..2)
area(areaId = GridAreaNames.Area4, row = 4, column = 2)
gap(4.dp)
},
modifier = Modifier.size(360.dp)
) {
PastelRedCard(
"Area 1",
// Use Modifier.gridItem(areaId) to place this composable into the
// grid area defined with the matching ID in the config block.
modifier = Modifier.gridItem(areaId = GridAreaNames.Area1)
)
PastelGreenCard(
"Area 2",
modifier = Modifier.gridItem(areaId = GridAreaNames.Area2)
)
PastelBlueCard(
"Area 3",
modifier = Modifier.gridItem(areaId = GridAreaNames.Area3)
)
PastelYellowCard(
"Area 4",
modifier = Modifier.gridItem(areaId = GridAreaNames.Area4)
)
}<br />
By using named areas, you can reorganize or adjust the physical layout grid (for
example, changing rows, columns, or track sizes) in the config lambda
without needing to modify the order or parameters of the child composables.
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- Google LLC
- Publisher
- Android (Google) (Official)
- Distributed by
- Android (Google)
- Source
- android/skills · jetpack-compose/adaptive · commit bf68e2d
- Licence
- Apache License 2.0 (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE.txt)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by Google LLC or Android (Google).
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download adaptive.zip