Display Glasses With Jetpack Compose Glimmer
Android (Google)OfficialCreated by Google LLCDistributed by Android (Google)
- Skill
- Tool integration
- 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 design principles, UI patterns, and development workflows for creating projected Android XR applications for display glasses. It focuses on the Jetpack Compose Glimmer toolkit, covering component usage, theming, input handling, and hardware integration for additive display environments.
What it does
- Defines Glimmer design principles and interaction models for display glasses.
- Provides guidance on setting up projected activities and managing device connectivity.
- Outlines UI component usage including cards, buttons, lists, and stacks.
- Details typography, color, and depth token usage for additive displays.
- Explains mapping hardware touchpad and gesture inputs to app actions.
- Offers patterns for voice input indicators and hardware access.
When to use it
- When developing Android XR apps specifically for display glasses.
- When implementing UI using the Jetpack Compose Glimmer toolkit.
- When designing interactions for one-dimensional hardware controls.
- When configuring apps to run as projected activities on connected eyewear.
Advantages
- Ensures consistent UI behavior across display glasses.
- Provides specific guidance for additive display rendering.
- Standardizes interaction patterns for limited input hardware.
- Facilitates proper integration with the Android XR projected context.
Usage examples
- “How do I set up a basic projected activity for display glasses?”
- The skill provides the AndroidManifest configuration and the necessary Activity setup, including the use of ProjectedDisplayController and GlimmerTheme.
- “What are the best practices for card layouts in Glimmer?”
- It explains how to use ActionCard for single actions and ButtonGroup with non-focusable cards to avoid focus contention.
- “How should I handle user input on display glasses?”
- The skill details mapping touchpad gestures like taps and swipes, and explains how to use System Back for navigation.
- “How do I implement a voice input indicator?”
- It provides a code pattern for using the VoiceInputIndicator component driven by SpeechRecognizer RMS changes.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/android/display-glasses-with-jetpack-compose-glimmer/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip display-glasses-with-jetpack-compose-glimmer.zip -d .agents/skills
Documentation by Google LLC
Glossary
| Term | Definition |
|---|---|
| Intelligent eyewear | Hands-free eyewear with speakers, camera, and microphone (audio-only or display glasses). |
| Display glasses | Eyewear with a private in-lens display for glanceable visuals that pair with audio. |
| Jetpack Compose Glimmer | Compose UI toolkit providing components, theming, and focus behavior for display glasses. |
| Projected activity | An Activity running on a phone host whose UI and input are projected to connected eyewear. |
| Projected device | An XR eyewear device connected to an Android host phone that projects app content to it. |
| GlimmerTheme | Root styling provider for GlimmerColors, GlimmerTypography, and GlimmerShapes. |
| Additive display | Display where black (#000000) renders as 100% transparent by adding light to the scene. |
| Augmented experiences | Lightweight, additive Android XR experiences that help users while they're on the go. |
| Visual angle | Perceived size in XR; minimum readable text is 0.6 degrees (about 18sp at 1 m). |
Prerequisites
Target
compileSdk37 or higher (compileSdk = 37orcompileSdk { version = release(37) }). UpdatecompileSdkto 37 if lower.When adding dependencies, follow the instructions in Create your first activity for intelligent eyewear:
androidx.xr.glimmer:glimmer(minimum1.0.0-alpha21, or catalog aliaslibs.androidx.glimmer)androidx.xr.glimmer:glimmer-google-fonts(minimum1.0.0-alpha21, or catalog aliaslibs.androidx.glimmer.google.fonts)androidx.xr.projected:projected(minimum1.0.0-alpha13, or catalog aliaslibs.androidx.xr.projectedorlibs.androidx.projected)Check
gradle/libs.versions.tomlfirst; if catalog entries exist, use them inapp/build.gradle.ktsand verify their versions meet the minimums. Never guess1.0.0-alpha01forglimmer-google-fonts.
Core constraints and limitations
Don't : Use
MaterialThemeor Material 3 components (androidx.compose.material3.*) inside Projected Activities or Glimmer UI.Do : Use
GlimmerThemeand Glimmer components (androidx.xr.glimmer.*).Do : Always pass
createGoogleSansFlexTypography()fromandroidx.xr.glimmer.googlefontsastypographyinGlimmerTheme.Specific hardware device models or unique capabilities aren't detailed.
Elevation : Material 3 shadow or elevation modifiers aren't supported. Use
ShadowScopeorDepthtokens from Jetpack Compose Glimmer.Typography limits: Minimum readable text size is 18sp (0.6°). Avoid "Thin" or "Hairline" weights, which shimmer on additive lenses.
1. Set up dependencies
Set up projected activity : When creating a projected activity, follow Create your first activity for intelligent eyewear and projectedcontext-source.md. Set
android:requiredDisplayCategorytoandroid.hardware.display.category.XR_PROJECTEDinAndroidManifest.xml:<activity android:name="com.example.xr.projected.ProjectedMainActivity" android:exported="true" android:requiredDisplayCategory="android.hardware.display.category.XR_PROJECTED"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.XR_PROJECTED_LAUNCHER"/> </intent-filter> </activity><br />
Mobile app integration : In the host phone app, add a button with
Text("Launch on Glasses"). ObserveProjectedContext.isProjectedDeviceConnected(context, coroutineContext)usingcollectAsStateWithLifecycle(initialValue = false)to set the button'senabledstate so it's disabled when glasses are disconnected. When clicked, launchGlassesMainActivityon the glasses display usingProjectedContext.createProjectedActivityOptions(context).toBundle()as shown in the following snippet:val options = ProjectedContext.createProjectedActivityOptions(context) val intent = Intent(context, ProjectedMainActivity::class.java) context.startActivity(intent, options.toBundle())<br />
UI library and font : When declaring the Glimmer, Google Fonts, and Projected artifacts in
app/build.gradle.kts, follow Declaring Jetpack Compose Glimmer Dependencies, and follow glimmersansflextypography-source.md when configuring Google Sans Flex usingcreateGoogleSansFlexTypography.Theming, initial focus, and black background : On additive displays, pure black (
Color.BlackorGlimmerTheme.colors.background) renders as 100% transparent. InonCreate(annotated with@OptIn(ExperimentalComposeUiApi::class)), setComposeUiFlags.isInitialFocusOnFocusableAvailable = true(androidx.compose.ui.ComposeUiFlags), wrap content inGlimmerTheme(typography = createGoogleSansFlexTypography()), and applyModifier.background(Color.Black)(orGlimmerTheme.colors.background) to the root container:@OptIn(ExperimentalProjectedApi::class) class ProjectedMainActivity : ComponentActivity() { private var displayController: ProjectedDisplayController? = null private var isVisualUiSupported by mutableStateOf(false) private var areVisualsOn by mutableStateOf(true) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) lifecycle.addObserver(object : DefaultLifecycleObserver { override fun onDestroy(owner: LifecycleOwner) { displayController?.close() displayController = null } }) initializeGlassesFeatures() setContent { GlimmerTheme { HomeScreen( areVisualsOn = areVisualsOn, isVisualUiSupported = isVisualUiSupported, onClose = { finish() } ) } } } private fun initializeGlassesFeatures() { lifecycleScope.launch { // Check device capabilities val projectedDeviceController = ProjectedDeviceController.create(this@ProjectedMainActivity) isVisualUiSupported = projectedDeviceController.capabilities.contains(CAPABILITY_VISUAL_UI) val controller = ProjectedDisplayController.create(this@ProjectedMainActivity) displayController = controller val observer = GlassesLifecycleObserver( context = this@ProjectedMainActivity, controller = controller, onVisualsChanged = { visualsOn -> areVisualsOn = visualsOn } ) lifecycle.addObserver(observer) } } }<br />
Hardware capabilities, permissions, and access : When checking hardware capabilities, requesting permissions, or accessing glasses hardware, follow Check device capabilities at runtime, Request hardware permissions, and Use a projected context to access hardware.
2. Minimize and translate the UI
Build UI with Jetpack Compose Glimmer components and use depth for priority.
Design from the bottom up and always bottom-align UI (
Alignment.BottomCenter).One thing at a time : Show one primary piece of information at a time (for example, using
VerticalStack) and avoid multiple simultaneous cards.Color contrast : When choosing colors, follow material-hct-source.md to maintain at least a 70% tone difference between foreground and background in HCT.
3. Map input controls
Map tap and swipe interactions to the glasses touchpad. Inputs are one-dimensional; avoid nesting scrolling controls.
Use System Back to dismiss temporary states or detailed views.
When implementing focus navigation and hardware input handling, follow Focus in Jetpack Compose Glimmer and Hardware Controls for display glasses. Focus movement is continuous for scrollable containers and discrete for elements like button rows.
4. Build with Jetpack Compose Glimmer
Implementing Glimmer styles
When accessing theme tokens using GlimmerTheme, follow
glimmertheme-source.md.
| Category | Token | Value / Role |
|---|---|---|
| Color | primary / secondary | #9BBFFF / #4C88E9 (Focal colors) |
| Color | positive / negative | #7AD48F (Confirmation) / #F57082 (Alert) |
| Color | background | #000000 (Pure black, renders 100% transparent) |
| Color | surface | #262626 (Use SurfaceDefaults.border for borders) |
| Shape | Standard / Small | RoundedCornerShape(36.dp) / RoundedCornerShape(12.dp) |
Typography scale (Google Sans Flex) and depth levels
Use Google Sans Flex with variable axes ROND = 100f, wdth = 100f, opsz
= 9f, and wght by role:
| Style | Size / Line-Height | Weight |
|---|---|---|
| Title Large / Medium / Small | 30/36.sp, 24/32.sp, 20/28.sp | 725 |
| Body Large / Medium / Small | 30/36.sp, 24/32.sp, 20/28.sp | 520 |
| Caption | 18.sp / 28.sp | 650 |
When simulating depth with DepthEffect and DepthEffectLevels, follow
deptheffect-source.md and deptheffectlevels-source.md: use level1
for resting cards and background UI, and level2 for focused or pressed
interactive UI.
Implementing Jetpack Compose Glimmer components
Cards, ActionCards, ImageCards, and ButtonGroups
Cards (androidx.xr.glimmer.Card) group related content into a single focal
point. Never embed a Card within a ListItem. When implementing cards, follow
the instructions in Jetpack Compose Glimmer: Cards, card-source.md,
and card-samples-source.md.
Clickable versus non-clickable card : Pass
onClick = { ... }if the entireCardacts as a trigger; omitonClickif informational. Control focus on non-clickable cards withfocusable: Boolean = true(such asCard(focusable = false)).Single primary action (
ActionCard) : When a card has a single primary button action anchored to its bottom edge, useandroidx.xr.glimmer.ActionCardinstead of placing aButtoninsideCard. Itsactionbutton takes focus directly:ActionCard( action = { Button(onClick = {}, trailingIcon = { Icon(FavoriteIcon, "Localized description") }) { Text("Send") } } ) { Text("This is a card with a title, leading icon, header image, and action") }<br />
Multiple actions (
CardandButtonGroup)---avoiding focus contention : When pairing a card with multiple action buttons, useandroidx.xr.glimmer.ButtonGroup(with optionalrememberButtonGroupState). Never nestButtonGroupinsideCard { ... }. Place a non-focusableCard(focusable = false)(withoutonClick) aboveButtonGroupas a sibling in aColumnso the card and buttons don't compete for focus:ButtonGroup(modifier = Modifier.fillMaxWidth()) { Button(onClick = {}) { Text("Button 1") } Button(onClick = {}) { Text("Button 2") } Button(onClick = {}) { Text("Button 3") } Button(onClick = {}) { Text("Button 4") } Button(onClick = {}) { Text("Button 5") } }<br />
Image cards : Use
ImageCard,LeadingImageCard, orTrailingImageCardto display prominent imagery alongside card text.
Buttons and ToggleButtons
When implementing buttons or toggle buttons, follow the instructions in Jetpack Compose Glimmer: Buttons, button-source.md, and button-samples-source.md.
Standard and icon buttons : Use
Buttonfor text actions (with optionalleadingIcon/trailingIcon) andIconButtonfor icon-only triggers (such as media next-track or previous-track buttons).Toggle buttons (
ToggleButtonandIconToggleButton) : UseToggleButtonorIconToggleButtonfor stateful on/off or play/pause controls that morph based onchecked:@Composable fun ToggleButtonWithLeadingIconSample() { var checked by remember { mutableStateOf(false) } ToggleButton( checked = checked, leadingIcon = { Icon( if (checked) FavoriteIcon else OutlinedFavoriteIcon, contentDescription = "Toggle favorite" ) }, onCheckedChange = { checked = it } ) { Text(if (checked) "On" else "Off") } }<br />
Title chips
TitleChip (androidx.xr.glimmer.TitleChip) is a non-interactive pill header
(three words or fewer, single line). When implementing title chips, follow the
instructions in Jetpack Compose Glimmer: Title Chips,
titlechip-source.md, and titlechip-samples-source.md.
Spatial spacing : When placing a standalone
TitleChipabove aCardorActionCard, center theTitleChiphorizontally and separate it from the card usingTitleChipDefaults.associatedContentSpacing(usingSpacerorArrangement.spacedBy(TitleChipDefaults.associatedContentSpacing)):@Composable fun TitleChipWithCardSample() { Column(horizontalAlignment = Alignment.CenterHorizontally) { TitleChip { Text("Title Chip") } Spacer(Modifier.height(TitleChipDefaults.associatedContentSpacing)) Card( title = { Text("Title") }, subtitle = { Text("Subtitle") }, leadingIcon = { Icon(FavoriteIcon, "Localized description") }, ) { Text("Card Content") } } }<br />
Icons
When adding icons or icon buttons, follow the instructions in Jetpack Compose Glimmer: Icons, icon-source.md, iconbutton-source.md, and iconsizes-source.md.
Sizing and interactivity : Size icons with
GlimmerTheme.iconSizes(small,medium,large). UseIconButtonorIconToggleButtonfor triggers andIconfor status indicators.Contrast and library : Never use pure black (
Color.Black) for icon tints; black renders as transparent. Use Material Symbols (600 weight, Rounded, Unfilled). Ifandroidx.compose.material:material-icons-*isn't inapp/build.gradle.kts, build vectors withImageVector.BuilderorpainterResourceinstead of importingandroidx.compose.material.icons.*.
Lists
Use GlimmerLazyColumn (androidx.xr.glimmer.list.GlimmerLazyColumn) for
homogeneous scrollable items. When building scrollable lists and list items,
follow the API definitions in list-source.md, listitem-source.md,
and liststate-source.md.
Always use
GlimmerLazyColumn: Never use foundationLazyColumn. ImportGlimmerLazyColumn,rememberGlimmerLazyListState, anditemsfromandroidx.xr.glimmer.list(itemis a scope member, not imported). For programmatic scrolling to the first item, hoistval listState = rememberGlimmerLazyListState()and calllistState.scrollToItem(0)orlistState.animateScrollToItem(0).Integrated title, spacing, and rows : Pass headers using
title = { TitleChip { Text("...") } }directly onGlimmerLazyColumn(not outside it), setverticalArrangement = Arrangement.spacedBy(20.dp), and render rows withandroidx.xr.glimmer.ListItem(onClick = { ... }, supportingLabel = { Text(...) }) { Text(...) }(pass the primary label as the trailingcontentlambda, notheadlineContent, and never nest aCardinsideListItem):@Composable fun GlimmerLazyColumnWithTitleChipSample() { val ingredientItems = listOf("Milk", "Flour", "Egg", "Salt", "Apples", "Butter", "Vanilla", "Sugar", "Cinnamon") GlimmerLazyColumn(title = { TitleChip { Text("Ingredients") } }) { items(ingredientItems) { text -> ListItem { Text(text) } } } }<br />
Stacks
Use VerticalStack (androidx.xr.glimmer.stack.VerticalStack) to display
heterogeneous cards one at a time (such as calendar, transit, and weather
cards). Never use a TitleChip with VerticalStack. When implementing a
VerticalStack, follow the API definitions in stack-source.md,
stackstate-source.md, and stackitemscope-source.md.
Bottom alignment, height (+66.dp), and
itemDecoration: AlignVerticalStacktoAlignment.BottomCenter, set its height to66.dptaller than the tallest card (maxCardHeight + 66.dp), and applyModifier.itemDecoration(CardDefaults.shape)to theCardinside everyitem { ... }block so background cards are clipped and masked:@Composable fun VerticalStackSample() { VerticalStack { item { Card { Text("Top Card") } } item { Card { Text("Second Card") } } item { Card { Text("Third Card") } } } }<br />
Horizontal pagers and animated text
Use GlimmerHorizontalPager
(androidx.xr.glimmer.pager.GlimmerHorizontalPager) with
rememberGlimmerPagerState(pageCount = { ... }) for horizontal card
walkthroughs (never foundation HorizontalPager).
Smooth text motion : Inside pager pages, configure Glimmer
Text(androidx.xr.glimmer.Text, neverandroidx.compose.material3.Text) withtextMotion = TextMotion.Animated(using.copy(textMotion = TextMotion.Animated)) for smooth rendering during snap transitions:// Hoist the pager state, specifying the total page count with a lambda. val pagerState = rememberGlimmerPagerState(pageCount = { 10 }) GlimmerHorizontalPager( state = pagerState, modifier = Modifier.fillMaxSize(), ) { page -> // Use Glimmer components like Card and Text for optimized glasses styling. Card(modifier = Modifier.fillMaxWidth()) { Text( text = "Page: $page", // Recommended: use TextMotion.Animated for smooth transitions in a pager. style = LocalTextStyle.current.copy(textMotion = TextMotion.Animated), ) } }<br />
Surface
Modifier.surface (androidx.xr.glimmer.surface) builds custom interactive
components (such as status badges without Card or Button). When creating
custom surfaces, follow the API definitions in surface-source.md.
Shared
MutableInteractionSourceand order : Create a singleremember { MutableInteractionSource() }and pass it to bothModifier.surface(interactionSource = interactionSource, ...)and.clickable(interactionSource = interactionSource, ...)(or.focusable), chaining.surface(...)before.clickable(...):@Composable fun FocusableSurfaceSample() { val interactionSource = remember { MutableInteractionSource() } Box( modifier = Modifier .size(100.dp) .surface(interactionSource = interactionSource) .focusable(interactionSource = interactionSource), contentAlignment = Alignment.Center ) { Text("Focusable") } } @Composable fun ClickableSurfaceSample() { val interactionSource = remember { MutableInteractionSource() } Box( modifier = Modifier .size(100.dp) .surface(interactionSource = interactionSource) .focusable(interactionSource = interactionSource) .clickable( interactionSource = interactionSource, indication = null ) { /* Handle click action */ }, contentAlignment = Alignment.Center ) { Text("Clickable") } }<br />
Voice input indicator and indirect pointer gestures
VoiceInputIndicatorandContainedVoiceInputIndicator: Pass alevellambda returning aFloatnormalized to0.0f..1.0f. When driven bySpeechRecognizer(RecognitionListener.onRmsChanged(rmsdB: Float)), normalize and clamprmsdBwith.coerceIn(0f, 1f):// Example state variable to hold the normalized level (0.0 to 1.0) // that the VoiceInputIndicator component expects. val audioLevel = MutableStateFlow(0f) // Initialize the Android SpeechRecognizer val speechRecognizer = SpeechRecognizer.createSpeechRecognizer(context) // Listener to capture speech events and audio level changes val listener = object : RecognitionListener { override fun onRmsChanged(rmsdB: Float) { // Normalize raw dB level to a 0.0-1.0 range. // Android SpeechRecognizer's rmsdB typically ranges from 0 to ~10. audioLevel.value = ((rmsdB - 1f) / 9f).coerceIn(0f, 1f) } // ... Implement other required RecognitionListener methods ... override fun onReadyForSpeech(params: Bundle?) {} override fun onBeginningOfSpeech() {} override fun onEndOfSpeech() {} override fun onError(error: Int) {} override fun onResults(results: Bundle?) {} override fun onPartialResults(partialResults: Bundle?) {} override fun onEvent(eventType: Int, params: Bundle?) {} override fun onBufferReceived(buffer: ByteArray?) {} } // Attach the listener to the recognizer speechRecognizer.setRecognitionListener(listener) // Create an intent to specify the recognition model and behavior val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply { putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM) } // Begin listening for audio input speechRecognizer.startListening(intent)<br />
@Composable fun VoiceInputExample(modifier: Modifier) { // Collect the flow as Compose State so the UI reacts to changes in real-time. val currentLevel by audioLevel.collectAsState() VoiceInputIndicator( // The VoiceInputIndicator component provides a visual "pulse" or indicator // that changes based on the 'level' lambda, which returns a Float between 0.0 and 1.0. level = { currentLevel }, modifier = modifier ) }<br />
Modifier.onIndirectPointerGesture: Handle low-level touchpad tap (onClick), forward swipe (onSwipeForward), and backward swipe (onSwipeBackward) gestures usingandroidx.xr.glimmer.onIndirectPointerGestureon a container made focusable (usingfocusTarget,focusable, orsurface(focusable = true)):@Composable fun OnIndirectPointerGestureSample() { var lastGesture by remember { mutableStateOf("None") } Box( modifier = Modifier.fillMaxSize() .onIndirectPointerGesture( enabled = true, onSwipeForward = { lastGesture = "Forward" }, onSwipeBackward = { lastGesture = "Backward" }, onClick = { lastGesture = "Click" }, ) .focusTarget(), contentAlignment = Alignment.Center, ) { Text("Last Gesture: $lastGesture") } }<br />
5. Integrate with system UI
When handling notifications or starting a projected activity from a notification, follow the instructions in Understand notification behavior for intelligent eyewear and Start a glasses activity on display glasses from a notification.
Files
- ATTRIBUTION.mdAdded by AutoGineer1.0 KiB
- LICENSELicence file added by AutoGineer11.1 KiB
- SKILL.md25.7 KiB
- references/android/design/ui/ai-glasses/guides/interaction/inputs.md4.6 KiB
- references/android/develop/xr/jetpack-xr-sdk/access-hardware-projected-context.md25.9 KiB
- references/android/develop/xr/jetpack-xr-sdk/request-hardware-permissions.md9.1 KiB
- references/button-samples-source.md4.9 KiB
- references/button-source.md9.7 KiB
- references/card-samples-source.md10.3 KiB
- references/card-source.md51.7 KiB
- references/deptheffect-source.md7.8 KiB
- references/deptheffectlevels-source.md4.1 KiB
- references/glimmersansflextypography-source.md11.3 KiB
- references/glimmertheme-source.md7.6 KiB
- references/icon-source.md16.8 KiB
- references/iconbutton-source.md4.8 KiB
- references/iconsizes-source.md2.3 KiB
- references/list-source.md713 B
- references/listitem-source.md11.2 KiB
- references/liststate-source.md17.8 KiB
- references/material-hct-source.md6.3 KiB
- references/projectedcontext-source.md12.9 KiB
- references/stack-source.md15.3 KiB
- references/stackitemscope-source.md16.2 KiB
- references/stackstate-source.md12.9 KiB
- references/surface-source.md32.3 KiB
- references/titlechip-samples-source.md2.9 KiB
- references/titlechip-source.md5.1 KiB
references/liststate-source.md
When creating a Glimmer List component, refer to the following source code in
GlimmerLazyListState.kt for creating a state for the list:
/*
* Copyright 2025 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.xr.glimmer.list
import androidx.annotation.IntRange
import androidx.compose.foundation.MutatePriority
import androidx.compose.foundation.ScrollIndicatorState
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.ScrollScope
import androidx.compose.foundation.gestures.ScrollableState
import androidx.compose.foundation.interaction.InteractionSource
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.lazy.layout.LazyLayoutPinnedItemList
import androidx.compose.runtime.Composable
import androidx.compose.runtime.annotation.FrequentlyChangingValue
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.neverEqualPolicy
import androidx.compose.runtime.saveable.Saver
import androidx.compose.runtime.saveable.listSaver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.layout.AlignmentLine
import androidx.compose.ui.layout.MeasureResult
import androidx.compose.ui.layout.Remeasurement
import androidx.compose.ui.layout.RemeasurementModifier
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Density
import androidx.xr.glimmer.list.GlimmerLazyListState.Companion.Saver
import kotlin.math.abs
/**
* Creates a [GlimmerLazyListState] that is remembered across compositions.
*
* Changes to the provided initial values will **not** result in the state being recreated or
* changed in any way if it has already been created.
*
* @param initialFirstVisibleItemIndex the initial value for
* [GlimmerLazyListState.firstVisibleItemIndex]
* @param initialFirstVisibleItemScrollOffset the initial value for
* [GlimmerLazyListState.firstVisibleItemScrollOffset]
*/
@Composable
public fun rememberGlimmerLazyListState(
initialFirstVisibleItemIndex: Int = 0,
initialFirstVisibleItemScrollOffset: Int = 0,
): GlimmerLazyListState =
rememberSaveable(saver = GlimmerLazyListState.Saver) {
GlimmerLazyListState(initialFirstVisibleItemIndex, initialFirstVisibleItemScrollOffset)
}
/**
* A state object that can be hoisted to control and observe scrolling.
*
* In most cases, this will be created via [rememberGlimmerLazyListState].
*
* @param firstVisibleItemIndex the initial value for [GlimmerLazyListState.firstVisibleItemIndex]
* @param firstVisibleItemScrollOffset the initial value for
* [GlimmerLazyListState.firstVisibleItemScrollOffset]
*/
public class GlimmerLazyListState(
firstVisibleItemIndex: Int = 0,
firstVisibleItemScrollOffset: Int = 0,
) : ScrollableState {
private val backingState = ScrollableState { -onScroll(-it) }
// TODO: b/414961654 - Consider making this abstraction around "anchor item".
/** The holder class for the current scroll position. */
private val scrollPosition =
GlimmerLazyListScrollPosition(firstVisibleItemIndex, firstVisibleItemScrollOffset)
/** Backing state for [layoutInfo] */
internal val layoutInfoState = mutableStateOf(EmptyLazyListMeasureResult, neverEqualPolicy())
private val density: Density
get() = layoutInfoState.value.density
/**
* This field is used to save information about the number of "beyond bounds items" that we want
* to compose. These items are not within the visible bounds of the lazy layout, but we compose
* them because they are explicitly requested through the
* [beyond bounds layout API][androidx.compose.ui.layout.BeyondBoundsLayout].
*/
internal val beyondBoundsInfo = LazyLayoutBeyondBoundsInfo()
/** Includes information for requesting focus for children as the list scrolls. */
internal val autoFocusState = GlimmerLazyListAutoFocusState()
/** Stores currently pinned items which are always composed. */
internal val pinnedItems = LazyLayoutPinnedItemList()
internal val internalInteractionSource: MutableInteractionSource = MutableInteractionSource()
/**
* The scroll amount was provided in `onScroll` to be consumed during the current measure pass.
*
* Scrolling forward is negative.
*/
internal var incomingScroll: Float = 0f
private set
/**
* This value retains the scroll amount that we want to carry over between measure passes. It
* represents the amount of scroll from previous passes that wasn't consumed back then but is
* awaiting to be consumed later. Together with [incomingScroll], this represents the total
* scroll available to the list during the current measure pass.
*
* This variable exists because the layout uses integer pixels while [onScroll] operates with
* fractional floats. Consequently, the list might receive tiny fractions of scroll input which,
* when aggregated, should equate to a few pixels of scrolling. However, because these small
* fractions are spread across many [onScroll] invocations, the list ignores them, making it
* feel unresponsive during slow, gentle touches. To avoid this, instead of ignoring these tiny
* scroll increments, the list accumulates them so they can be added to the next scroll part and
* actually consumed in a subsequent pass.
*
* Note that this value can sometimes be opposite to the scroll direction. This occurs because
* the [Float] -> [Int] rounding causes us to consume more than was provided. To compensate, we
* add a negative value to [incomingScroll] the next time.
*
* Scrolling forward is negative.
*/
internal var carryOverScroll: Float = 0f
private set
/**
* This value is updated after the measure pass inside [applyMeasureResult] and defines how much
* of the [incomingScroll] was actually used.
*/
private var consumedScroll: Float = 0f
internal val nearestRange: kotlin.ranges.IntRange by
LazyLayoutNearestRangeState(0, NearestItemsSlidingWindowSize, NearestItemsExtraItemCount)
/**
* The [Remeasurement] object associated with our layout. It allows us to remeasure
* synchronously during scroll.
*/
internal var remeasurement: Remeasurement? = null
private set
/** The modifier which provides [remeasurement]. */
internal val remeasurementModifier =
object : RemeasurementModifier {
override fun onRemeasurementAvailable(remeasurement: Remeasurement) {
[email protected] = remeasurement
}
}
/**
* Provides a modifier which allows to delay some interactions (e.g. scroll) until layout is
* ready.
*/
internal val awaitLayoutModifier = AwaitFirstLayoutModifier()
/**
* The index of the first item that is visible within the scrollable viewport area not including
* items in the content padding region. For the first visible item that includes items in the
* content padding please use [GlimmerLazyListLayoutInfo.visibleItemsInfo].
*
* Note that this property is observable and if you use it in the composable function it will be
* recomposed on every change causing potential performance issues.
*/
public val firstVisibleItemIndex: Int
@FrequentlyChangingValue get() = scrollPosition.index
/**
* The scroll offset of the first visible item. Scrolling forward is positive - i.e., the amount
* that the item is offset backwards.
*
* Note that this property is observable and if you use it in the composable function it will be
* recomposed on every scroll causing potential performance issues.
*/
public val firstVisibleItemScrollOffset: Int
@FrequentlyChangingValue get() = scrollPosition.scrollOffset
/**
* The object of [GlimmerLazyListLayoutInfo] calculated during the last layout pass. For
* example, you can use it to calculate what items are currently visible.
*
* Note that this property is observable and is updated after every scroll or remeasure. If you
* use it in the composable function it will be recomposed on every change causing potential
* performance issues including infinity recomposition loop. Therefore, avoid using it in the
* composition.
*
* If you want to run some side effects like sending an analytics event or updating a state
* based on this value consider using "snapshotFlow":
*/
public val layoutInfo: GlimmerLazyListLayoutInfo
@FrequentlyChangingValue get() = layoutInfoState.value
/**
* [InteractionSource] that will be used to dispatch drag events when this list is being
* dragged. If you want to know whether the fling (or animated scroll) is in progress, use
* [isScrollInProgress].
*/
public val interactionSource: InteractionSource
get() = internalInteractionSource
/** Snaps to the requested scroll position. */
internal fun snapToItemIndexInternal(index: Int, scrollOffset: Int) {
scrollPosition.requestPositionAndForgetLastKnownKey(index, scrollOffset)
remeasurement?.forceRemeasure()
}
/**
* When the user provided custom keys for the items we can try to detect when there were items
* added or removed before our current first visible item and keep this item as the first
* visible one even given that its index has been changed.
*/
internal fun updateScrollPositionIfTheFirstItemWasMoved(
itemProvider: GlimmerLazyListItemProvider,
firstItemIndex: Int,
): Int = scrollPosition.updateScrollPositionIfTheFirstItemWasMoved(itemProvider, firstItemIndex)
/**
* Called during the measurement pass once the dispatched [incomingScroll] has been handled and
* the new item positions are known.
*
* @param result lazy list measuring results.
* @param consumedScroll defines how much scroll was consumed during the measure pass.
* @param scrollToCarryOver tracks the amount of scrolling that the internal logic has reported
* as consumed, but wants to save for later measurement. Also, if the list consumes more
* scroll than it was given (for example, due to rounding errors), this value can be set to a
* negative amount to balance it out in the next pass. This value should never be larger than
* [consumedScroll].
*/
internal fun applyMeasureResult(
result: GlimmerLazyListMeasureResult,
consumedScroll: Float,
scrollToCarryOver: Float,
) {
this.consumedScroll = consumedScroll
this.carryOverScroll = scrollToCarryOver
canScrollBackward = result.canScrollBackward
canScrollForward = result.canScrollForward
layoutInfoState.value = result
scrollPosition.updateFromMeasureResult(result)
}
internal fun onScroll(distance: Float): Float {
if (distance < 0 && !canScrollForward || distance > 0 && !canScrollBackward) {
return 0f
}
// Fast path. Skip measure pass.
if (abs(distance + carryOverScroll) <= 0.5f) {
// Inside measuring we do `scrollToBeConsumed.roundToInt()` so there will be no scroll
// if we have less than 0.5 pixels. So just accumulate it for the next pass.
carryOverScroll += distance
return distance
}
incomingScroll = distance
// The `forceRemeasure()` invocation triggers the measure pass where [incomingScroll]
// will be used to update [consumedScroll] and [carryOverScroll] values.
remeasurement?.forceRemeasure()
// It's important to reset this value because there are measure passes
// triggered from outside scrolling. They read this value as well.
// So, after we used it, we need to reset it to zero.
incomingScroll = 0f
return consumedScroll
}
override suspend fun scroll(
scrollPriority: MutatePriority,
block: suspend ScrollScope.() -> Unit,
) {
awaitLayoutModifier.waitForFirstLayout()
backingState.scroll(scrollPriority, block)
}
override fun dispatchRawDelta(delta: Float): Float = backingState.dispatchRawDelta(delta)
override val isScrollInProgress: Boolean
get() = backingState.isScrollInProgress
@get:Suppress("GetterSetterNames")
override var canScrollForward: Boolean by mutableStateOf(false)
private set
@get:Suppress("GetterSetterNames")
override var canScrollBackward: Boolean by mutableStateOf(false)
private set
override val scrollIndicatorState: ScrollIndicatorState
get() = _scrollIndicatorState
private val _scrollIndicatorState =
object : ScrollIndicatorState {
override val scrollOffset: Int
@FrequentlyChangingValue
get() =
with(layoutInfoState.value) {
if (this === EmptyLazyListMeasureResult) {
Int.MAX_VALUE
} else {
[email protected] *
visibleItemsAverageSize +
[email protected]
}
}
override val contentSize: Int
@FrequentlyChangingValue
get() =
with(layoutInfoState.value) {
if (this === EmptyLazyListMeasureResult) {
Int.MAX_VALUE
} else {
// Approximate size of all content
(totalItemsCount * visibleItemsAverageSize) -
// Subtract the final trailing spacing that is not shown
(if (totalItemsCount > 0) mainAxisItemSpacing else 0) +
// Add the inner paddings (which are separate from the item sizes)
beforeContentPadding +
afterContentPadding
}
}
override val viewportSize: Int
get() =
with(layoutInfoState.value) {
if (this === EmptyLazyListMeasureResult) {
Int.MAX_VALUE
} else {
mainAxisViewportSize
}
}
}
/**
* Instantly brings the item at [index] to the top of the viewport, offset by [scrollOffset]
* pixels.
*
* @param index the index to which to scroll. Must be non-negative.
* @param scrollOffset the offset that the item should end up after the scroll. Note that
* positive offset refers to forward scroll, so in a top-to-bottom list, positive offset will
* scroll the item further upward (taking it partly offscreen).
*/
public suspend fun scrollToItem(@IntRange(from = 0) index: Int, scrollOffset: Int = 0) {
scroll { snapToItemIndexInternal(index, scrollOffset) }
}
/**
* Animate (smooth scroll) to the given item.
*
* @param index the index to which to scroll. Must be non-negative.
* @param scrollOffset the offset that the item should end up after the scroll. Note that
* positive offset refers to forward scroll, so in a top-to-bottom list, positive offset will
* scroll the item further upward (taking it partly offscreen).
*/
public suspend fun animateScrollToItem(@IntRange(from = 0) index: Int, scrollOffset: Int = 0) {
scroll {
GlimmerLazyListScrollScope(this@GlimmerLazyListState, this)
.animateScrollToItem(index, scrollOffset, NumberOfItemsToTeleport, density)
}
}
public companion object {
/** The default [Saver] implementation for [GlimmerLazyListState]. */
public val Saver: Saver<GlimmerLazyListState, Any> =
listSaver(
save = { listOf(it.firstVisibleItemIndex, it.firstVisibleItemScrollOffset) },
restore = {
GlimmerLazyListState(
firstVisibleItemIndex = it[0],
firstVisibleItemScrollOffset = it[1],
)
},
)
}
}
private val EmptyLazyListMeasureResult =
GlimmerLazyListMeasureResult(
firstVisibleItem = null,
firstVisibleItemScrollOffset = 0,
canScrollForward = false,
consumedScroll = 0f,
measureResult =
object : MeasureResult {
override val width: Int = 0
override val height: Int = 0
@Suppress("PrimitiveInCollection")
override val alignmentLines: Map<AlignmentLine, Int> = emptyMap()
override fun placeChildren() {}
},
visibleItemsInfo = emptyList(),
viewportStartOffset = 0,
viewportEndOffset = 0,
totalItemsCount = 0,
reverseLayout = false,
orientation = Orientation.Vertical,
afterContentPadding = 0,
mainAxisItemSpacing = 0,
remeasureNeeded = false,
density = Density(1f),
childConstraints = Constraints(),
)<br />
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 · xr/display-glasses-with-jetpack-compose-glimmer · 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 display-glasses-with-jetpack-compose-glimmer.zip