Leanback To Compose Tv Migration
Android (Google)OfficialCreated by Google LLCDistributed by Android (Google)
- Skill
- Guidelines
- 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, five-phase migration strategy for transitioning Android TV applications from the legacy Leanback UI Toolkit and View-based fragments to Jetpack Compose for TV (androidx.tv). It covers architectural patterns, D-pad focus management, media playback integration using Media3, and component mapping to ensure a modern, performant 10-foot UI experience.
What it does
- Maps legacy Leanback classes to modern Jetpack Compose for TV equivalents.
- Defines architectural patterns for 10-foot UI design and navigation.
- Provides implementation details for D-pad focus handling and focus recollection.
- Outlines a phased migration strategy from foundation to final cleanup.
- Details integration of Media3 Compose for video playback and transport controls.
- Offers best practices for handling text input and IME focus chaining on TV.
When to use it
- When modernizing an existing Android TV application built with Leanback or Fragments.
- When replacing legacy components like BrowseSupportFragment or VideoSupportFragment.
- When implementing new TV-optimized layouts using Jetpack Compose.
- When troubleshooting D-pad navigation or focus issues in a Compose-based TV app.
Advantages
- Ensures consistent D-pad navigation and focus behavior.
- Reduces technical debt by replacing legacy View-based components.
- Provides clear, actionable steps for a phased, low-risk migration.
- Aligns with modern Android development standards for TV.
Usage examples
- “How do I replace a BrowseSupportFragment in my Android TV app?”
- The skill provides a mapping to a BrowseScreen using LazyColumn and LazyRow, along with guidance on implementing immersive list architecture.
- “How can I ensure my Compose TV app handles D-pad focus correctly?”
- The skill explains using FocusRequester for initial focus and Modifier.focusRestorer for maintaining focus state in lazy lists.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/android/leanback-to-compose-tv-migration/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip leanback-to-compose-tv-migration.zip -d .agents/skills
Documentation by Google LLC
The 10-foot UI
A "10-foot UI" is a design paradigm for televisions that tailors an interface for viewing from approximately 3 meters (10 feet) away. When designing for this experience, account for these key characteristics:
Viewing distance: Viewers are sitting far from the screen, "leaning back". Screen layouts are uncluttered, with text and UI elements that are large enough to be comfortably readable from a distance, without dense blocks of text.
Color contrast: To avoid washed out colors on TV displays with low contrast ratios, the design uses high-contrast palettes and distinct visual indicators so focused states remain visible across different TV panels.
D-pad navigation : Interaction relies on a directional remote control with limited 4-way navigation (
Up,Down,Left,Right) with components organized into clear spatial grids and carousels without focus traps.
Core architecture and library selection
When migrating an Android TV application to Jetpack Compose, you must use
androidx.tv libraries and follow these 10-foot UI patterns:
UI modernization: Focus on custom, cinematic layouts over legacy direct 1:1 templates. You must use Jetpack Compose for TV features like dynamic gradient hero backdrops, custom focus animations, custom navigation drawers, and custom layouts.
Primary design system : You must always use
androidx.tv.material3.*(androidx.tv:tv-material) over mobileandroidx.compose.material3.*. TV Material 3 provides built-in D-Pad focus handling, focus zoom scaling, and TV-optimized typography and shapes. To set up Compose for TV dependencies, follow Compose for TV setup.Focus zoom animation : For interactive cards, you must use
CompactCard,ClassicCard, orWideCardContainerwithscale = CardDefaults.scale(focusedScale = 1.1f)to provide standard TV focus animation.Coil image loading : To use declarative
AsyncImage(model, contentDescription, ...)without passing an explicitImageLoaderparameter, you must includeio.coil-kt:coil-composein your Gradle dependencies.Explicit imports : You must always import TV Material 3 classes explicitly (for example,
import androidx.tv.material3.Surface,import androidx.tv.material3.ListItem) instead of using wildcard imports (import androidx.tv.material3.*).File naming conventions : You must name Composable screen files after the screen (for example, name
BrowseScreenasBrowseScreen.kt,PlaybackScreenasPlaybackScreen.kt, andAuthenticationScreenasAuthenticationScreen.kt). Don't use generic prefixes likeMain.Overscan and bezels : You must apply horizontal padding (for example,
horizontal = 48.dpor32.dp,vertical = 24.dp) to root containers, carousels, and top bars to prevent clipping.Reading width constrainment : You must constrain reading width using
Modifier.widthIn(max = 600.dp)on text columns for long-form text.Media3 Compose dependencies : Include
androidx.media3:media3-ui-composeinapp/build.gradlewhen modernizing media playback screens.Prohibition of legacy AndroidView wrappers : Don't use legacy
AndroidViewwrappers to embed View-based components into Jetpack Compose screens. All migrated screens must use Compose components or Media3 Compose surfaces (PlayerSurface).
D-pad focus handling and navigation
Jetpack Compose for TV (androidx.tv.material3) requires explicit focus
management, as components don't receive initial focus automatically and
navigation uses 2D spatial coordinates. To configure TV D-pad navigation, follow
instructions in TV Navigation guide.
Initial focus
You must assign initial focus to the primary interactive element on every screen
(such as the first action button, card, or ListItem) using FocusRequester
when entering a screen. Define val focusRequester = remember { FocusRequester() }, attach Modifier.focusRequester(focusRequester) to the primary element, and
request focus inside LaunchedEffect(Unit) { focusRequester.requestFocus() }:
val focusRequester = remember { FocusRequester() }
val focusManager = LocalFocusManager.current
LaunchedEffect(Unit) {
focusRequester.requestFocus()
}<br />
Note: For screens with dynamic state or pagers (like OnboardingScreen using
HorizontalPager), you must pass the state key to LaunchedEffect (for example
LaunchedEffect(pagerState.currentPage)) so that focus is re-applied when the
page changes.
Bidirectional focus routing and avoiding focus traps
When interactive elements sit on opposite sides of the display, standard 2D spatial navigation fails to find targets across them. This creates focus traps where users are unable to navigate out of an area using the D-pad.
For symmetrical, bidirectional D-pad navigation without focus traps, you must
rely on Compose's 2D spatial focus engine whenever possible. When connecting
adjacent UI elements across scrollable containers (like LazyColumn or
LazyRow), don't set directional overrides (up = ..., down = ...) targeting
individual items inside lazy lists. When an item scrolls off-screen during
vertical navigation, its FocusRequester becomes uninitialized, throwing
IllegalStateException during focus searches:
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 48.dp, vertical = 16.dp),
horizontalArrangement = Arrangement.End
) {
Button(
onClick = { /* Search */ },
modifier = Modifier.focusRequester(topBarFocusRequester)
) { Text("Search") }
}<br />
Row focus recollection (Modifier.focusRestorer)
When navigating vertically between horizontal carousels (LazyRow), Compose's
default 2D spatial focus engine searches along the X coordinate of the focused
item. If a user scrolls right in Row 1 (for example to Item 4 at X=800dp) and
presses DOWN to navigate to Row 2, spatial routing focuses whatever item sits at
X=800dp in Row 2.
To make every row maintain its own recollection of card focus (restoring focus
to the previously visited item when revisited), you must attach
Modifier.focusRestorer (with no arguments) directly to the LazyRow.
Don't pass custom fallback FocusRequester lambdas in lazy containers, as
calling requestFocus on an unattached or off-screen item during rapid D-pad
scrolling throws IllegalStateException.
LazyRow(
modifier = Modifier.focusRestorer(),
contentPadding = PaddingValues(horizontal = 48.dp),
horizontalArrangement = Arrangement.spacedBy(16.dp)
) {
itemsIndexed(videos) { vidIndex, video ->
CompactCard(
onClick = { onVideoClick(video) },
image = {
AsyncImage(
model = video.cardImageUrl,
contentDescription = video.title,
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxSize()
)
},
title = { Text(video.title) },
modifier = Modifier
.then(
if (catIndex == 0 && vidIndex == 0) {
Modifier.focusRequester(firstCardFocusRequester)
} else {
Modifier
}
)
.onFocusChanged { focusState ->
if (focusState.isFocused) {
focusedVideo = video
focusedCategoryIndex = catIndex
}
}
)
}
}<br />
Text input, hardware keyboard enter interception, and IME focus chaining
When migrating search bars or login forms from Leanback
(SearchSupportFragment, GuidedStepSupportFragment), don't use bare
BasicTextField containers or empty Surface(onClick = {}) wrappers, as they
prevent D-pad CENTER from attaching the virtual keyboard (IME).
Clickable TV surface wrapper with Back-key interception (
onPreviewKeyEvent) : Wrap standard M3TextFieldinside a focusable TVSurface(onClick = { focusRequester.requestFocus() }, scale = ClickableSurfaceDefaults.scale(focusedScale = 1.01f), border = ClickableSurfaceDefaults.border(focusedBorder = Border(BorderStroke(2.dp, Color.White))))to provide a focused border outline and D-pad focus scaling. You must attachModifier.onPreviewKeyEventon the text field or wrapper to interceptKey.BackandKey.Escapeso the user's able to remove focus from the input field without exiting the screen.Why Back-key interception is mandatory : When editing a text field on Android TV, pressing the D-pad Back button normally navigates back and exits the screen. By intercepting
Key.BackandKey.EscapeonKeyUpinonPreviewKeyEventto stop editing (clearing focus), the user's able to return to D-pad form navigation without being trapped in the text field or accidentally exiting the screen.IME focus chaining : For multi-field forms (such as Username and Password in authentication screens), attach
KeyboardActions(onNext = { focusManager.moveFocus(FocusDirection.Down) })withImeAction.Nexton top fields to route focus down to the next input box, andImeAction.Doneon the bottom field to route focus directly to the submit button:
Surface(
onClick = { focusRequester.requestFocus() },
border = ClickableSurfaceDefaults.border(focusedBorder = Border(border = BorderStroke(2.dp, Color.White))),
modifier = Modifier
.fillMaxWidth()
.focusRequester(focusRequester)
) {
OutlinedTextField(
value = username,
onValueChange = { username = it },
label = { Text("Username") },
singleLine = true,
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
keyboardActions = KeyboardActions(onNext = { focusManager.moveFocus(FocusDirection.Down) }),
modifier = Modifier
.fillMaxWidth()
.onPreviewKeyEvent { event ->
if (event.type == KeyEventType.KeyDown && (event.key == Key.Enter || event.key == Key.NumPadEnter)) {
focusManager.moveFocus(FocusDirection.Down)
true
} else false
}
)
}
Surface(
onClick = {},
border = ClickableSurfaceDefaults.border(focusedBorder = Border(border = BorderStroke(2.dp, Color.White))),
modifier = Modifier.fillMaxWidth()
) {
OutlinedTextField(
value = password,
onValueChange = { password = it },
label = { Text("Password") },
singleLine = true,
visualTransformation = PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
keyboardActions = KeyboardActions(onDone = { onLoginSuccess() }),
modifier = Modifier
.fillMaxWidth()
.onPreviewKeyEvent { event ->
if (event.type == KeyEventType.KeyDown && (event.key == Key.Enter || event.key == Key.NumPadEnter)) {
onLoginSuccess()
true
} else false
}
)
}<br />
Lazy containers
When implementing scrollable lists or grids in Jetpack Compose for TV, you must
use standard LazyColumn, LazyRow, and LazyVerticalGrid from
androidx.compose.foundation.lazy and androidx.compose.foundation.lazy.grid.
For catalog browsing layouts, follow instructions in Catalog Browser guide.
Pivot scrolling with
BringIntoViewSpec: When defining a custom pivot scroll line for catalog rows usingBringIntoViewSpecandCompositionLocalProvider(LocalBringIntoViewSpec provides ...), you must ensure your project compiles against Compose Foundation 1.7.0+ by addingimplementation platform('androidx.compose:compose-bom:2024.06.00')(or newer) orimplementation 'androidx.compose.foundation:foundation:1.7.0'inapp/build.gradle. Without Compose Foundation 1.7.0+,import androidx.compose.foundation.gestures.LocalBringIntoViewSpecwill fail withUnresolved reference: LocalBringIntoViewSpec.Row focus recollection (
Modifier.focusRestorer) : Annotate your composable with@OptIn(ExperimentalFocusRestorerApi::class, ExperimentalComposeUiApi::class)and attachModifier.focusRestoreron every categoryLazyRowto remember and restore the last focused card when navigating vertically across catalog rows.
When populated with focusable TV Material 3 components (CompactCard,
ListItem, Button), standard Compose lazy containers handle 2D D-Pad focus
routing, focus memory, and edge scrolling automatically:
@Composable
fun CatalogBrowser(
featuredContentList: List<Movie>,
sectionList: List<Section>,
modifier: Modifier = Modifier,
onItemSelected: (Movie) -> Unit = {},
) {
LazyColumn(
modifier = modifier.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
items(sectionList.size) { index ->
val section = sectionList[index]
SectionRow(section, onItemSelected = onItemSelected)
}
}
}<br />
Media3 video playback and transport controls
When migrating legacy Leanback video playback (VideoSupportFragment /
PlaybackGlue), use Compose Media3 PlayerSurface
(androidx.media3.ui.compose.PlayerSurface) combined with a translucent
transport controls overlay:
Mandatory Media3 transport control buttons (
PlayPauseButton) : Over thePlayerSurface, you must layer a translucent bottom controls bar (Box(modifier = Modifier.align(Alignment.BottomCenter))) containing explicit Media3 UI Compose buttons: at minimumPlayPauseButton,SeekBackButton, andSeekForwardButton. Never leave the transport controls overlay empty. To use these composables, you must addimplementation 'androidx.media3:media3-ui-compose-material3:1.6.0'alongsideandroidx.media3:media3-ui-composein yourapp/build.gradledependencies.D-pad directional seeking (
onPreviewKeyEvent) : To support seeking backward and forward with the remote control D-pad, attachModifier.onPreviewKeyEventon the container or controls overlay and intercept ComposeKey.DirectionLeftandKey.DirectionRight(for example,keyEvent.key == Key.DirectionLeft) to seek backward and forward by 10 seconds (exoPlayer.seekTo(exoPlayer.currentPosition - 10000)). Never use legacy Android View keycodes (KeyEvent.KEYCODE_DPAD_LEFTornativeKeyEvent.keyCode).Prohibition of legacy AndroidView wrappers : Don't wrap legacy
PlayerVieworStyledPlayerViewinAndroidView { ... }. You must usePlayerSurface(androidx.media3.ui.compose.PlayerSurface) withExoPlayerfor video rendering in Compose for TV.
Phased migration strategy
To migrate an app cleanly without breaking compilation or introducing circular dependencies, execute in five distinct phases:
Phase 1: Foundation and design system
Phase 2: Leaf and standalone screens
Phase 3: Core browsing and discovery screens
Phase 4: Details and media playback
Phase 5: Final unification and cleanup
Phase 1: Foundation and design system
Create
TvTheme.ktwrappingTvMaterialThemewith customColorScheme,Typography, andShapes.Build atomic reusable components:
MovieCard,SectionHeader,LoadingIndicator,ErrorState.
Phase 2: Leaf and standalone screens
Migrate screens with no outbound navigation first, such as error messages, onboarding screens, or settings screens, by replacing them with
ErrorDialog,OnboardingScreen, andSettingsScreen.Replace anything using
BaseLeanbackPreferenceFragmentCompat,BaseLeanbackPreferenceFragment, orLeanbackSettingsFragmentto use Compose, for example by usingListItem+Switchbound directly toSharedPreferencesand replacing thefindPreferenceimplementation.Ensure screens receive initial D-pad focus on the first or main component of that screen using
FocusRequester, for example on the firstListItem.Replace legacy
Fragmentclasses with activities of typeComponentActivitythat declaratively use components in Compose.Clean up legacy style and theme references in
res/values/styles.xmlandres/values/themes.xml(such as removingpreferenceThemethat points to@style/PreferenceThemeOverlay.v14.Leanback) that aren't supported once leanback dependencies are removed:
@Composable
fun TvSettingsScreen(
modifier: Modifier = Modifier
) {
var autoPlayNext by remember { mutableStateOf(true) }
var highQualityAudio by remember { mutableStateOf(false) }
Column(
modifier = modifier
.fillMaxSize()
.padding(48.dp)
) {
Text(
text = "Settings",
style = MaterialTheme.typography.headlineMedium,
modifier = Modifier.padding(bottom = 24.dp)
)
LazyColumn(
verticalArrangement = Arrangement.spacedBy(12.dp),
contentPadding = PaddingValues(vertical = 8.dp)
) {
item {
ListItem(
selected = false,
onClick = { autoPlayNext = !autoPlayNext },
headlineContent = { Text("Autoplay Next Video") },
supportingContent = { Text("Automatically start playing next item in queue") },
trailingContent = {
Switch(
checked = autoPlayNext,
onCheckedChange = null
)
}
)
}
item {
ListItem(
selected = false,
onClick = { highQualityAudio = !highQualityAudio },
headlineContent = { Text("High Quality Audio") },
supportingContent = { Text("Use spatial audio and multi-channel output when available") },
trailingContent = {
Switch(
checked = highQualityAudio,
onCheckedChange = null
)
}
)
}
}
}
}<br />
Phase 3: Core browsing and discovery screens
Migrate
VerticalGridScreen(LazyVerticalGrid),SearchScreen(BasicTextFieldwith live list filtering), andBrowseScreen(LazyColumnofLazyRows).Eradicate legacy
ArrayObjectAdapter,ListRowPresenter,CardPresenter, andHeaderItemclasses.
Phase 4: Details and media playback
Migrate
VideoDetailsScreenandGuidedStepScreen.Migrate
PlaybackScreenusing Compose Media3PlayerSurface(androidx.media3.ui.compose.PlayerSurface) paired with a translucent bottom overlay containing Media3 Compose transport controls (such asPlayPauseButton,SeekBackButton,SeekForwardButton).
Phase 5: Final unification and cleanup
Remove all remaining legacy
.javaactivities, fragments, presenters, and XML layout files.Ensure all activities extend
ComponentActivityorFragmentActivitycallingsetContent { ... }.Completely remove legacy Leanback themes and style declarations from
res/values/styles.xmlandres/values/themes.xml(for example, any styles inheriting fromTheme.Leanbackor referencinglb_styles).
Component and class mapping guide
| Legacy Leanback / View Class | Modern Jetpack Compose Equivalent |
|---|---|
BrowseSupportFragment / MainFragment | BrowseScreen (LazyColumn containing categorized LazyRows + Hero Banner) |
DetailsSupportFragment | VideoDetailsScreen (Poster image, text column, action buttons, related LazyRow) |
VideoSupportFragment / PlaybackGlue | PlaybackScreen (Media3 ExoPlayer + Compose PlayerSurface) |
GuidedStepSupportFragment | GuidedStepScreen (Split-screen layout: 40% left guidance pane, 60% right actions pane) |
SearchSupportFragment | SearchScreen (BasicTextField + live filtering + LazyVerticalGrid) |
VerticalGridSupportFragment | VerticalGridScreen (LazyVerticalGrid(columns = GridCells.Fixed(5))) |
ArrayObjectAdapter / Presenter | Declarative @Composable functions observing immutable State<List<T>> |
CursorMapper / LoaderManager / CursorLoader | Kotlin Coroutines / withContext(Dispatchers.IO) in a Repository object |
OnboardingSupportFragment | OnboardingScreen (HorizontalPager + D-Pad navigation buttons) |
LeanbackSettingsFragment / PreferenceFragment | SettingsScreen (FocusRequester on first ListItem + trailing Switch bound to SharedPreferences) |
Reference implementations and battle-tested patterns
Modern TV immersive list architecture (BrowseScreen)
When building a 10-foot TV browse screen or Immersive List, don't place a hero
banner before or outside a scrolling list, and don't fight Compose's automatic
BringIntoView system with programmatic animateScrollToItem calls.
Instead, use BringIntoViewSpec with LocalBringIntoViewSpec from Compose
Foundation to define exact TV pivot scrolling (for example, pivoting active rows
at 35% from the top edge of the display). Combine this with a reshaping
immersive row: when lower rows are focused (focusedCategoryIndex > 0), hide
the hero text and display a normal section header on Row 0:
@Composable
fun ImmersiveBrowseScreen(
categories: Map<String, List<Video>>,
onVideoClick: (Video) -> Unit
) {
var focusedVideo by remember { mutableStateOf<Video?>(null) }
var focusedCategoryIndex by remember { mutableStateOf(0) }
val listState = rememberLazyListState()
val topBarFocusRequester = remember { FocusRequester() }
val firstCardFocusRequester = remember { FocusRequester() }
Box(modifier = Modifier.fillMaxSize()) {
AsyncImage(
model = focusedVideo?.bgImageUrl,
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxSize()
)
PositionFocusedItemInLazyLayout(parentFraction = 0.35f, childFraction = 0.5f) {
LazyColumn(
state = listState,
contentPadding = PaddingValues(top = 36.dp, bottom = 64.dp),
verticalArrangement = Arrangement.spacedBy(28.dp),
modifier = Modifier.fillMaxSize()
) {
item {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 48.dp, vertical = 16.dp),
horizontalArrangement = Arrangement.End
) {
Button(
onClick = { /* Search */ },
modifier = Modifier.focusRequester(topBarFocusRequester)
) { Text("Search") }
}
}
itemsIndexed(categories.entries.toList()) { catIndex, (categoryName, videos) ->
Column {
if (catIndex == 0 && focusedCategoryIndex == 0) {
Column(
modifier = Modifier
.heightIn(min = 200.dp)
.padding(horizontal = 48.dp)
) {
Text(
text = focusedVideo?.title ?: "",
style = MaterialTheme.typography.displayMedium
)
Text(
text = focusedVideo?.description ?: "",
style = MaterialTheme.typography.bodyLarge
)
}
} else {
Text(
text = categoryName,
style = MaterialTheme.typography.titleMedium,
modifier = Modifier.padding(horizontal = 48.dp, vertical = 8.dp)
)
}
LazyRow(
modifier = Modifier.focusRestorer(),
contentPadding = PaddingValues(horizontal = 48.dp),
horizontalArrangement = Arrangement.spacedBy(16.dp)
) {
itemsIndexed(videos) { vidIndex, video ->
CompactCard(
onClick = { onVideoClick(video) },
image = {
AsyncImage(
model = video.cardImageUrl,
contentDescription = video.title,
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxSize()
)
},
title = { Text(video.title) },
modifier = Modifier
.then(
if (catIndex == 0 && vidIndex == 0) {
Modifier.focusRequester(firstCardFocusRequester)
} else {
Modifier
}
)
.onFocusChanged { focusState ->
if (focusState.isFocused) {
focusedVideo = video
focusedCategoryIndex = catIndex
}
}
)
}
}
}
}
}
}
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun PositionFocusedItemInLazyLayout(
parentFraction: Float = 0.35f,
childFraction: Float = 0.5f,
content: @Composable () -> Unit,
) {
val bringIntoViewSpec = remember(parentFraction, childFraction) {
object : BringIntoViewSpec {
override fun calculateScrollDistance(
offset: Float,
size: Float,
containerSize: Float
): Float {
if (offset >= 0f && offset <= containerSize * 0.45f) {
return 0f
}
val initialTargetForLeadingEdge = parentFraction * containerSize - (childFraction * size)
val targetForLeadingEdge = if (size <= containerSize && (containerSize - initialTargetForLeadingEdge) < size) {
containerSize - size
} else {
initialTargetForLeadingEdge
}
return offset - targetForLeadingEdge
}
}
}
CompositionLocalProvider(LocalBringIntoViewSpec provides bringIntoViewSpec, content = content)
}<br />
Media3 playback in Compose TV (PlaybackScreen)
Implement a custom playback screen using
androidx.media3.ui.compose.PlayerSurface as the video rendering canvas. Layer
Material3 transport controls (SeekBackButton, PlayPauseButton,
SeekForwardButton from androidx.media3:media3-ui-compose-material3) over the
surface in a translucent bottom overlay, and handle D-pad remote key events with
an auto-hide timeout:
@OptIn(UnstableApi::class)
@Composable
fun Media3PlaybackScreen(
video: Video,
onFinish: () -> Unit,
modifier: Modifier = Modifier
) {
val context = LocalContext.current
val exoPlayer = remember(context) { ExoPlayer.Builder(context).build() }
var showControls by remember { mutableStateOf(true) }
val focusRequester = remember { FocusRequester() }
val coroutineScope = rememberCoroutineScope()
var autoHideJob by remember { mutableStateOf<Job?>(null) }
fun scheduleAutoHide() {
autoHideJob?.cancel()
autoHideJob = coroutineScope.launch {
delay(5000)
showControls = false
}
}
DisposableEffect(exoPlayer) {
val listener = object : Player.Listener {
override fun onPlaybackStateChanged(playbackState: Int) {
if (playbackState == Player.STATE_ENDED) {
onFinish()
}
}
}
exoPlayer.addListener(listener)
onDispose {
autoHideJob?.cancel()
exoPlayer.removeListener(listener)
exoPlayer.release()
}
}
LaunchedEffect(video) {
focusRequester.requestFocus()
scheduleAutoHide()
val mediaItem = MediaItem.fromUri(video.videoUrl)
exoPlayer.setMediaItem(mediaItem)
exoPlayer.prepare()
exoPlayer.playWhenReady = true
}
Box(
modifier = modifier
.fillMaxSize()
.background(Color.Black)
.focusRequester(focusRequester)
.focusable()
.onPreviewKeyEvent { event ->
if (event.type == KeyEventType.KeyDown) {
when (event.key) {
Key.DirectionCenter, Key.Enter, Key.NumPadEnter, Key.MediaPlayPause, Key.Spacebar -> {
if (exoPlayer.isPlaying) exoPlayer.pause() else exoPlayer.play()
showControls = true
scheduleAutoHide()
true
}
Key.DirectionLeft, Key.MediaRewind -> {
val newPos = (exoPlayer.currentPosition - 10_000L).coerceAtLeast(0L)
exoPlayer.seekTo(newPos)
showControls = true
scheduleAutoHide()
true
}
Key.DirectionRight, Key.MediaFastForward -> {
val duration = exoPlayer.duration.coerceAtLeast(0L)
val newPos = (exoPlayer.currentPosition + 10_000L).coerceAtMost(duration)
exoPlayer.seekTo(newPos)
showControls = true
scheduleAutoHide()
true
}
Key.DirectionUp, Key.DirectionDown -> {
showControls = !showControls
if (showControls) scheduleAutoHide() else autoHideJob?.cancel()
true
}
else -> false
}
} else false
},
contentAlignment = Alignment.Center
) {
PlayerSurface(
player = exoPlayer,
modifier = Modifier.fillMaxSize()
)
if (showControls) {
Box(
modifier = Modifier
.fillMaxSize()
.background(Color(0x80000000))
.padding(48.dp),
contentAlignment = Alignment.BottomCenter
) {
Row(
horizontalArrangement = Arrangement.spacedBy(24.dp),
verticalAlignment = Alignment.CenterVertically
) {
SeekBackButton(player = exoPlayer)
PlayPauseButton(player = exoPlayer)
SeekForwardButton(player = exoPlayer)
}
}
}
}
}<br />
Replacing CursorLoader with reactive coroutine flow
Replace legacy LoaderManager.LoaderCallbacks<Cursor> and CursorObjectAdapter
with a repository returning a Flow that observes database changes and triggers
asynchronous fetching when empty:
object VideoFlowRepository {
fun getVideosFlow(context: Context, contentUri: Uri): Flow<List<Video>> = callbackFlow {
val contentObserver = object : ContentObserver(Handler(Looper.getMainLooper())) {
override fun onChange(selfChange: Boolean) {
trySend(queryVideos(context, contentUri))
}
}
context.contentResolver.registerContentObserver(
contentUri,
true,
contentObserver
)
val initialVideos = queryVideos(context, contentUri)
trySend(initialVideos)
awaitClose {
context.contentResolver.unregisterContentObserver(contentObserver)
}
}.flowOn(Dispatchers.IO)
private fun queryVideos(context: Context, uri: Uri): List<Video> {
// Query database or ContentProvider
return emptyList()
}
}<br />
Files
- ATTRIBUTION.mdAdded by AutoGineer999 B
- LICENSELicence file added by AutoGineer11.1 KiB
- SKILL.md34.0 KiB
- references/android/training/tv/get-started/navigation.md16.9 KiB
- references/android/training/tv/playback/compose/browse.md9.7 KiB
- references/android/training/tv/playback/compose/index.md7.6 KiB
references/android/training/tv/get-started/navigation.md
TV devices provide a limited set of navigation controls for apps. Creating an effective navigation scheme for your TV app depends on understanding these limited controls as well as users' limitations while operating your app. As you build your Android app for TV, pay special attention to how the user navigates when using remote control buttons instead of a touchscreen.
Principles
The goal is for navigation to feel natural and familiar without dominating the user interface or diverting attention from content. The following principles help set a baseline for a consistent and intuitive user experience across TV apps. Efficient
Simplify getting to content. Users want to access content quickly, using a minimal number of clicks. Organize your information in a way that requires the fewest screens. Predictable
Follow best practices and recommendations to make navigation predictable to users. Don't reinvent navigation patterns unnecessarily, as this leads to confusion and unpredictability. Intuitive
Simplify navigation enough to seamlessly support widely adopted user behaviors. Don't over-complicate by adding unnecessary layers of navigation.
Controllers
Controllers come in a variety of styles, from a minimalist remote control to complex game controllers. All controllers include a directional pad (D-pad) plus select, home, and back buttons. Other buttons vary by model. Image: A television remote control Figure 1. Example of a TV remote.
D-pad
The primary navigation method on TV is through the D-pad, which includes up, down, left, and right directional hardware buttons. The D-pad transfers focus from one object to the nearest object in the direction of the button pressed.
Select button
Selects the on-screen item with focus.
Home button
Takes the user to the system Home screen.
Back button
Gives users a way to return to the previous view.
Microphone button
Invokes either Google Assistant or voice input.
<br />
[!NOTE] Note: The remote control shown in figure 1 is for reference only. There are many layouts and styles of remotes and controllers, though all of them have the basic functionality described here. For more information, see Manage TV controllers.
D-pad navigation
On a TV device, users navigate using either a D-pad or arrow keys. This type of control limits movement to up, down, left, and right. To build a great TV-optimized app, you must provide a navigation scheme where the user can quickly learn how to navigate your app using these limited controls.
The Android framework handles directional navigation between layout elements automatically, so you typically don't need to do anything extra for your app. However, you should thoroughly test navigation with a D-pad controller to discover any navigation problems.
Follow these guidelines to test that your app's navigation system works well with a D-pad on a TV device:
Ensure that a user with a D-pad controller can navigate to all visible controls on the screen.
For scrolling lists with focus, make sure that the D-pad up and down buttons scroll the list and that the select button selects an item in the list. Verify that users can select an element in the list and that the list still scrolls when an element is selected.
Ensure that switching between controls is straightforward and predictable.
Modify directional navigation
The Android framework automatically applies a directional navigation scheme based on the relative position of focusable elements in your layouts. Test the generated navigation scheme in your app using a D-pad controller. After testing, if you decide that you want users to move through your layouts in a specific way, you can set up explicit directional navigation for your controls.
[!NOTE] Note: Only use these attributes to modify the navigation order if the default order that the system applies does not work well.
The following code sample shows how to define the next control to receive focus
for a TextView layout object:
<TextView android:id="@+id/Category1" android:nextFocusDown="@+id/Category2" />The following table lists all of the available navigation attributes for Android user interface widgets:
| Attribute | Function |
|---|---|
nextFocusDown | Defines the next view to receive focus when the user navigates down. |
nextFocusLeft | Defines the next view to receive focus when the user navigates left. |
nextFocusRight | Defines the next view to receive focus when the user navigates right. |
nextFocusUp | Defines the next view to receive focus when the user navigates up. |
To use one of these explicit navigation attributes, set the value to the
android:id of another widget in the layout. Be sure to set up the
navigation order as a loop, so that the last control directs focus back to the
first one.
Provide clear focus and selection
The success of an app's navigation scheme on TV devices depends on whether a user can quickly determine what user interface element is in focus. If you don't provide a clear indication of the focused item, and therefore what item a user can take action on, they can quickly become frustrated and exit your app. For the same reason, it is important to always have an item in focus that a user can take action on immediately after your app starts or any time it is idle.
In your app layout and implementation, use color, size, animation, or a combination of these attributes to help users determine what actions they can take next. Use a uniform scheme for indicating focus across your application.
Android provides Drawable state list resources to implement highlights for focused and selected controls. The following code example demonstrates how to enable visual behavior for a button to indicate that a user has navigated to the control and then selected it:
<!-- res/drawable/button.xml -->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="@drawable/button_pressed" /> <!-- pressed -->
<item android:state_focused="true"
android:drawable="@drawable/button_focused" /> <!-- focused -->
<item android:state_hovered="true"
android:drawable="@drawable/button_focused" /> <!-- hovered -->
<item android:drawable="@drawable/button_normal" /> <!-- default -->
</selector><br />
The following layout XML sample code applies the previous state list drawable to
a Button:
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:background="@drawable/button" />Make sure to provide sufficient padding within the focusable and selectable controls so that the highlights around them are clearly visible.
Back button navigation
For consistency across apps on the platform, ensure the behavior of the back button follows these guidelines.
Use predictable back button behavior
To create a straightforward and predictable navigation experience, when the user presses the remote's back button, take them to the previous destination. Image: The flow of navigation when using top navigation Figure 2. Flow using top navigation. Image: The flow of navigation when using side navigation Figure 3. Flow using side navigation.
If the user navigates from a menu item to a card on the middle of the page and then presses the back button, the result depends on whether the app uses top navigation or left navigation:
App uses top navigation: take the user back to the top of the page by scrolling quickly and activating focus on the menu.
App uses left navigation: activate the left side menu and focus on the currently active menu item.
Ensure that the back button isn't gated by confirmation screens or part of an infinite loop. Image: A dialog asking users if they want to exit Figure 4. Exit gating Don't.
Avoid exit gating. Let users exit out of the app without confirmation.
<br />
Image: Navigation looping between closing and opening the menu Figure 5. Navigation loop Don't.
Never enter the infinite loop of closing and opening the menu. Ideally, pressing the back button exits out of the app. Don't show an exit button on the menu unless it's a special case, such as a kids profile.
Don't display an up or back button
Unlike on handheld devices, the back button on the remote is used to navigate backward on a TV. It's not necessary to show a virtual back button on the screen: Image: A virtual back button displayed on the screen Figure 6. Soft back button
Don't.
<br />
<br />
Show a cancel button if necessary
If the only visible actions are confirming, destructive, or purchase actions, it's good practice to have a Cancel button that returns to the previous destination: Image: A cancel button displayed alongside destructive actions Figure 7. Soft cancel button.
Do.
<br />
Implement back navigation
The Android framework generally handles back navigation well, as it does for the D-pad. If you use the Navigation component, you can support a variety of navigation graphs. Occasionally, you might need to implement some custom behavior, such as having the back button reset the focus to the beginning of a long list.
ComponentActivity,
the base class for FragmentActivity
and AppCompatActivity,
lets you control the behavior of the back button by using its
OnBackPressedDispatcher,
which you can retrieve by calling getOnBackPressedDispatcher().
For more information, see Provide custom back navigation.
Playback controls on TV
Video playback is one of the most important features on TV. It's important that video players in apps across Android TV behave the same. Refer to the playback controls guidelines for TV.
Live tab navigation
In addition to complying with the TV app quality requirements, apps with a live TV feed integrated on the Live tab must also meet frictionless playback and direct-back requirements, as described in the following sections.
[!NOTE] Note: These requirements will be enforced beginning in the first half of 2023 only for partners with a linear feed integrated on the Live tab. Failure to comply will result in the partner no longer being integrated on the Live tab.
Frictionless playback
Frictionless playback applies to in-app behavior following any Live or Linear channel deep link from Google TV and Android TV.
When a user clicks a deep link, the following rules apply:
No delays: Users must be led directly to channel playback without blocking or delaying screens, such as sign-in or sign-up flows or branding videos.
Cold boot exception: If the deep link initiates the target app loading from a cold boot, the boot-up delay is permitted. App boot-up branding videos or animations are also allowed in this case.
Loading delay exception: If tuning into the channel takes a few seconds, displaying branding is permitted. The duration must only be as long as it takes to load the channel.
If the user is signed out or isn't subscribed, you can block playback for a paid channel to complete a sign-in or sign-up flow.
Direct-back
When users launch an app from a deep link on the Live tab, then press the back button, they must be returned to the Live tab in a single back press, regardless of how much time has elapsed. This direct-back behavior is required for all Live tab deep links on Google TV and Android TV.
Live tab deep links are distinguished by an appended deep link parameter:
?exit_on_back=[true|false]. Apps must parse this parameter to determine
whether the app was launched from the Live tab. If exit_on_back is true,
apps must implement the direct-back behavior.
Note that if the user presses any button other than back button as the first button press after the deep link, then the direct-back requirement doesn't apply, and only the standard back button behavior is required.
For example, suppose after following a deep link the user presses the D-pad's select button, which brings up a controls overlay. The user waits for the overlay to disappear, and then presses the back button. Since the first button pressed after following the deep link was the D-pad select button, the direct-back requirement does not apply. Instead, the normal app back stack logic applies.
Repeated presses of the back button must lead the user to the app root and then back to Google TV or Android TV, without any infinite loops. For more information, see the Predictable back button behavior section.
Navigation architecture
A well-defined navigation architecture helps users understand where they are in your app and how to access different content. Consider the following aspects of navigation design.
Fixed start destination
The first screen the user sees when they launch the app from the launcher is also the last screen the user sees when they return to the launcher after pressing the back button.
[!NOTE] Note: Some apps display a splash screen while preparing the main app UI. Don't include a splash screen in the back stack.
Deep linking simulates manual navigation
Whether deep linking or manually navigating to a specific destination, users can use the back button to navigate through destinations back to the start destination. Image: Screenshots showing a deep link into a details page within an app. Pressing back goes to that app's home screen and pressing back again returns to the original screen. Figure 8. Deep linking to a details page.
Deep linking into an app from another app simulates manual navigation. For example, if the user goes directly to a details page on the Moviestar app from Google TV and then presses the back button, they are taken to the home page of the Moviestar app.
<br />
[!NOTE] Note: This does not apply when launching from the Live Tab for direct playback. See the Live Tab navigation section for details.
Clear path to all focusable elements
Let users navigate your UI with clear direction. If there isn't a straight path to get to a control, consider relocating it. Image: A layout with controls placed in non-overlapping locations Figure 9. Control focusability.
Do.
Place controls, like the search action shown here, in locations that don't overlap with other clickable elements. Image: A layout with controls in hard-to-reach locations Figure 10. Control focusability.
Don't.
Avoid layouts that contain controls in hard-to-reach places. Reaching the search action shown here might be difficult with the D-pad.
Axes
Design your layout to take advantage of both horizontal and vertical axes. Give each direction a specific function, making it fast to navigate large hierarchies. Image: A layout using vertical categories and horizontal items Figure 11. Traversal.
Do.
Categories can be traversed on the vertical axis, and items within each category can be browsed on the horizontal axis. Image: A complex and nested layout hierarchy Figure 12. Traversal.
Don't.
Avoid complex and nested layout hierarchies.
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 · tv/leanback-to-compose-tv-migration · 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 leanback-to-compose-tv-migration.zip