car: fix template loading crashes, use chips and sections
- Commit
0801daac6b500fda5babfd4fee377b781fb6089b- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-19 18:10 UTC (2 months ago)
- Parents
e2ba176
Diff
communicate/src/main/java/com/vayunmathur/communicate/service/car/CommunicateCarCallScreen.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/service/car/CommunicateCarCallScreen.kt b/communicate/src/main/java/com/vayunmathur/communicate/service/car/CommunicateCarCallScreen.ktindex 320e10ce4a..d50eb4f32b 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/service/car/CommunicateCarCallScreen.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/service/car/CommunicateCarCallScreen.kt@@ -125,12 +125,14 @@ class CommunicateCarCallScreen( } private fun callAction(title: String, onClick: () -> Unit): Action {- val icon = runCatching {- CarIcon.Builder(IconCompat.createWithResource(carContext, R.mipmap.ic_launcher)).build()- }.getOrNull()- val builder = Action.Builder().setOnClickListener(onClick)- if (icon != null) builder.setIcon(icon) else builder.setTitle(title)- return builder.build()+ // IN_CALL_CONTENT requires icons and allows zero custom titles, so+ // actions are icon-only. The launcher icon stands in: music ships no+ // playback drawables and titles are rejected here.+ val icon = CarIcon.Builder(IconCompat.createWithResource(carContext, R.mipmap.ic_launcher)).build()+ return Action.Builder()+ .setIcon(icon)+ .setOnClickListener(onClick)+ .build() } private fun placeCall(number: String) {
communicate/src/main/java/com/vayunmathur/communicate/service/car/CommunicateCarConversationScreen.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/service/car/CommunicateCarConversationScreen.kt b/communicate/src/main/java/com/vayunmathur/communicate/service/car/CommunicateCarConversationScreen.ktindex 3fc6cdad6d..b6080e329a 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/service/car/CommunicateCarConversationScreen.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/service/car/CommunicateCarConversationScreen.kt@@ -66,6 +66,9 @@ class CommunicateCarConversationScreen( @OptIn(ExperimentalCarApi::class) private fun conversationTemplate(): Template { val title = thread.displayName?.takeIf { it.isNotBlank() } ?: thread.address+ // ConversationItem requires a non-empty message list — before the+ // messages load, show the legacy list (which handles loading itself).+ if (messages.isEmpty()) return legacyListTemplate() val self = Person.Builder().setName("You").setKey("self").build() val carMessages = messages.map { message -> val sender = if (message.outgoing) {@@ -111,8 +114,9 @@ class CommunicateCarConversationScreen( .setGroupConversation(thread.isGroup) .build() val list = ItemList.Builder().addItem(item).build()- return ListTemplate.Builder()- .setSingleList(list)+ // ListTemplate.build() throws when loading==hasList: only set the+ // list once messages have loaded.+ val listBuilder = ListTemplate.Builder() .setHeader( androidx.car.app.model.Header.Builder() .setStartHeaderAction(Action.BACK)@@ -120,7 +124,10 @@ class CommunicateCarConversationScreen( .build(), ) .setLoading(loading)- .build()+ if (!loading) {+ listBuilder.setSingleList(list)+ }+ return listBuilder.build() } private fun legacyListTemplate(): Template {
communicate/src/main/java/com/vayunmathur/communicate/service/car/CommunicateCarThreadListScreen.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/service/car/CommunicateCarThreadListScreen.kt b/communicate/src/main/java/com/vayunmathur/communicate/service/car/CommunicateCarThreadListScreen.ktindex 206edf680a..1f3b57b43b 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/service/car/CommunicateCarThreadListScreen.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/service/car/CommunicateCarThreadListScreen.kt@@ -3,16 +3,26 @@ package com.vayunmathur.communicate.service.car import androidx.car.app.CarContext import androidx.car.app.Screen import androidx.car.app.model.Action+import androidx.car.app.model.Header import androidx.car.app.model.ItemList import androidx.car.app.model.ListTemplate import androidx.car.app.model.Row+import androidx.car.app.model.RowSection+import androidx.car.app.model.SectionedItemTemplate import androidx.car.app.model.Template+import com.vayunmathur.communicate.data.CommunicateLine import com.vayunmathur.communicate.data.SmsThread /** * Merged conversation list: SIM + GoogleVoice + WhatsApp + Signal threads, * newest first. *+ * Component choice (car design guide):+ * - API 8+: [SectionedItemTemplate] with one [RowSection] per line (SIM,+ * Google Voice, WhatsApp, Signal) — section headers label each group, so+ * the driver sees where each thread lives without opening it.+ * - Older hosts: the flat [ListTemplate] fallback.+ * * Rows show the display name, snippet, and unread state; tapping opens * [CommunicateCarConversationScreen]. GoogleVoice rows carry no reply * affordance (read-only until the token follow-up) but stay readable.@@ -34,22 +44,80 @@ class CommunicateCarThreadListScreen( } override fun onGetTemplate(): Template {- val list = ItemList.Builder()- for (thread in threads) {- val title = thread.displayName?.takeIf { it.isNotBlank() } ?: thread.address- val row = Row.Builder()- .setTitle(title)- thread.snippet.takeIf { it.isNotBlank() }?.let { row.addText(it) }- row.setBrowsable(true)- row.setOnClickListener {- screenManager.push(CommunicateCarConversationScreen(carContext, session, thread))+ // ListTemplate.build() throws when loading==hasList, and an empty+ // section set is legal — but while loading there is nothing to show,+ // so both paths branch on it.+ if (carContext.getCarAppApiLevel() >= 8) {+ runCatching { return sectionedTemplate() }+ }+ return legacyListTemplate()+ }++ private fun sectionedTemplate(): Template {+ val builder = SectionedItemTemplate.Builder()+ .setHeader(+ Header.Builder()+ .setStartHeaderAction(Action.APP_ICON)+ .setTitle(if (loading) "Loading…" else "Messages")+ .build(),+ )+ .setLoading(loading)+ if (!loading) {+ for ((line, label) in LINE_ORDER) {+ val rows = threads.filter { it.line == line }.map { threadRow(it) }+ if (rows.isNotEmpty()) {+ builder.addSection(+ RowSection.Builder()+ .setTitle(label)+ .setItems(rows)+ .build(),+ )+ }+ }+ }+ return builder.build()+ }++ private fun legacyListTemplate(): Template {+ val listBuilder = ListTemplate.Builder()+ .setHeader(+ Header.Builder()+ .setStartHeaderAction(Action.APP_ICON)+ .setTitle(if (loading) "Loading…" else "Messages")+ .build(),+ )+ .setLoading(loading)+ if (!loading) {+ val list = ItemList.Builder()+ for (thread in threads) {+ list.addItem(threadRow(thread)) }- list.addItem(row.build())+ listBuilder.setSingleList(list.build())+ }+ return listBuilder.build()+ }++ private fun threadRow(thread: SmsThread): Row {+ val title = thread.displayName?.takeIf { it.isNotBlank() } ?: thread.address+ val row = Row.Builder()+ .setTitle(title)+ thread.snippet.takeIf { it.isNotBlank() }?.let { row.addText(it) }+ if (thread.unreadCount > 0) {+ row.addText("${thread.unreadCount} unread") }- return ListTemplate.Builder()- .setSingleList(list.build())- .setTitle(if (loading) "Loading…" else "Messages")- .setHeaderAction(Action.APP_ICON)- .build()+ row.setBrowsable(true)+ row.setOnClickListener {+ screenManager.push(CommunicateCarConversationScreen(carContext, session, thread))+ }+ return row.build()+ }++ private companion object {+ val LINE_ORDER: List<Pair<CommunicateLine, String>> = listOf(+ CommunicateLine.Sim to "SIM",+ CommunicateLine.GoogleVoice to "Google Voice",+ CommunicateLine.WhatsApp to "WhatsApp",+ CommunicateLine.Signal to "Signal",+ ) } }
maps/src/main/java/com/vayunmathur/maps/car/CarSearchScreen.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/car/CarSearchScreen.kt b/maps/src/main/java/com/vayunmathur/maps/car/CarSearchScreen.ktindex ffcb013676..6f7632966a 100644--- a/maps/src/main/java/com/vayunmathur/maps/car/CarSearchScreen.kt+++ b/maps/src/main/java/com/vayunmathur/maps/car/CarSearchScreen.kt@@ -80,14 +80,16 @@ class CarSearchScreen(carContext: CarContext) : Screen(carContext) { // List|Pane|Grid|Message (+SectionedItem on API 8+), so search is a // ListTemplate with the voice action in the action strip. The typed // SearchTemplate shape can't nest inside map content.- val listTemplate = androidx.car.app.model.ListTemplate.Builder()+ //+ // ListTemplate.build() throws when loading==hasList, so the loading+ // state must NOT set a list.+ val listBuilder = androidx.car.app.model.ListTemplate.Builder() .setHeader( Header.Builder() .setStartHeaderAction(Action.BACK) .setTitle(carContext.getString(R.string.car_search_title)) .build() )- .setSingleList(buildItemList()) .setActionStrip( ActionStrip.Builder() .addAction(@@ -99,9 +101,11 @@ class CarSearchScreen(carContext: CarContext) : Screen(carContext) { .build() ) .setLoading(loading)- .build()+ if (!loading) {+ listBuilder.setSingleList(buildItemList())+ } return MapWithContentTemplate.Builder()- .setContentTemplate(listTemplate)+ .setContentTemplate(listBuilder.build()) .build() }
music/src/main/java/com/vayunmathur/music/service/car/MusicCarBrowseScreen.kt
diff --git a/music/src/main/java/com/vayunmathur/music/service/car/MusicCarBrowseScreen.kt b/music/src/main/java/com/vayunmathur/music/service/car/MusicCarBrowseScreen.ktindex a4ab598c08..c516f6b0ac 100644--- a/music/src/main/java/com/vayunmathur/music/service/car/MusicCarBrowseScreen.kt+++ b/music/src/main/java/com/vayunmathur/music/service/car/MusicCarBrowseScreen.kt@@ -3,10 +3,18 @@ package com.vayunmathur.music.service.car import androidx.car.app.CarContext import androidx.car.app.Screen import androidx.car.app.model.Action+import androidx.car.app.model.CarText+import androidx.car.app.model.Header import androidx.car.app.model.ItemList import androidx.car.app.model.ListTemplate import androidx.car.app.model.Row+import androidx.car.app.model.RowSection+import androidx.car.app.model.SectionedItemTemplate+import androidx.car.app.model.Tab+import androidx.car.app.model.TabContents+import androidx.car.app.model.TabTemplate import androidx.car.app.model.Template+import androidx.media3.common.MediaItem import com.vayunmathur.music.service.MusicLibraryTree /**@@ -17,6 +25,14 @@ import com.vayunmathur.music.service.MusicLibraryTree * session, then open [MusicCarPlaybackScreen]. A header play action plays * everything listed. Long lists stay parked-safe: rows are plain text, * artwork loads host-side from the item URIs.+ *+ * Component choice (car design guide):+ * - Root uses [TabTemplate] (API 6+): the five library tabs are exactly what+ * tabs are for. Each tab's content is a [SectionedItemTemplate] (API 8+) of+ * condensed song rows so more fits on screen; older hosts get [ListTemplate].+ * - Deeper levels use [SectionedItemTemplate] with one [RowSection] per+ * grouping; the list fallback covers API 1–7 hosts.+ * - The Play-all affordance is a single FAB (media apps get max 1 on API 9+). */ class MusicCarBrowseScreen( carContext: CarContext,@@ -29,21 +45,155 @@ class MusicCarBrowseScreen( } override fun onGetTemplate(): Template {+ // Root: tabs over sectioned content (API 6+). Fall back to the plain+ // list when the host is too old for tabs.+ if (nodeId == MusicLibraryTree.ROOT && carContext.getCarAppApiLevel() >= 6) {+ runCatching { return tabTemplate() }+ }+ // API 8+: sectioned content with a real section header per grouping.+ if (carContext.getCarAppApiLevel() >= 8) {+ runCatching { return sectionedTemplate() }+ }+ return legacyListTemplate()+ }++ // ------------------------------------------------------------------+ // TabTemplate (root, API 6+)+ // ------------------------------------------------------------------++ /** Tab ids in display order with their labels. */+ private fun rootTabs(): List<Pair<String, String>> {+ val tree = state.tree+ return listOf(+ MusicLibraryTree.TAB_PLAYLISTS,+ MusicLibraryTree.TAB_ALBUMS,+ MusicLibraryTree.TAB_ARTISTS,+ MusicLibraryTree.TAB_SONGS,+ MusicLibraryTree.TAB_RECENT,+ ).map { id -> id to (tree.item(id)?.mediaMetadata?.title?.toString() ?: id) }+ }++ @OptIn(androidx.car.app.annotations.ExperimentalCarApi::class)+ private fun tabTemplate(): Template {+ val tabs = rootTabs()+ val active = activeTabId(tabs)+ val content: Template = if (carContext.getCarAppApiLevel() >= 8) {+ sectionedContent(active, tabs.toMap()[active] ?: active)+ } else {+ listContent(active, tabs.toMap()[active] ?: active)+ }+ val builder = TabTemplate.Builder(+ object : TabTemplate.TabCallback {+ override fun onTabSelected(tabContentId: String) {+ screenManager.push(MusicCarBrowseScreen(carContext, tabContentId, state))+ }+ },+ )+ for ((id, label) in tabs) {+ builder.addTab(+ Tab.Builder()+ .setTitle(label)+ .setContentId(id)+ .build(),+ )+ }+ return builder+ .setTabContents(TabContents.Builder(content).build())+ .setActiveTabContentId(active)+ .setHeaderAction(Action.APP_ICON)+ .build()+ }++ /** The tab the user drilled from, or Songs at root. */+ private fun activeTabId(tabs: List<Pair<String, String>>): String {+ val top = screenManager.screenStack.toList()+ val parent = if (top.size >= 2) top[top.size - 2] else null+ val id = (parent as? MusicCarBrowseScreen)?.nodeId+ return id?.takeIf { tabs.any { (tabId, _) -> tabId == it } } ?: MusicLibraryTree.TAB_SONGS+ }++ // ------------------------------------------------------------------+ // SectionedItemTemplate (API 8+)+ // ------------------------------------------------------------------++ private fun sectionedTemplate(): Template { val tree = state.tree val title = tree.item(nodeId)?.mediaMetadata?.title?.toString() ?: "Music"- val items = tree.children(nodeId)- val list = ItemList.Builder()- if (nodeId != MusicLibraryTree.ROOT && items.isEmpty()) {- list.addItem(- Row.Builder()- .setTitle("Loading…")+ val builder = SectionedItemTemplate.Builder()+ // API 9+: ChipSection first — quick actions (shuffle all, play all).+ // Chips are for exactly this: compact filter/trigger actions.+ if (carContext.getCarAppApiLevel() >= 9) {+ runCatching { builder.addSection(quickActionChips()) }+ }+ return builder+ .addSection(+ RowSection.Builder()+ .setTitle(title)+ .setItems(songRows(tree.children(nodeId)))+ .build(),+ )+ .setHeader(+ Header.Builder()+ .setStartHeaderAction(Action.BACK)+ .setTitle(title)+ .build(),+ )+ .apply { playAllAction()?.let { addAction(it) } }+ .build()+ }++ /** Quick-action chips: shuffle-all and play-all. */+ @OptIn(androidx.car.app.annotations.ExperimentalCarApi::class)+ private fun quickActionChips(): androidx.car.app.model.ChipSection {+ val items = state.tree.children(nodeId)+ val section = androidx.car.app.model.ChipSection.Builder()+ section.addItem(+ androidx.car.app.model.Chip.Builder()+ .setTitle("Shuffle all")+ .setOnClickListener { shuffleAll(items.map { it.mediaId }) }+ .build(),+ )+ if (items.any { it.mediaMetadata.isPlayable == true && it.mediaMetadata.isBrowsable != true }) {+ section.addItem(+ androidx.car.app.model.Chip.Builder()+ .setTitle("Play all")+ .setOnClickListener { playAll(items.map { it.mediaId }) } .build(), ) }- for (item in items) {+ return section.build()+ }++ private fun shuffleAll(mediaIds: List<String>) {+ val playables = mediaIds.mapNotNull { state.tree.resolveForPlayback(it) }.shuffled()+ if (playables.isEmpty()) return+ val controller = state.controller ?: return+ controller.setMediaItems(playables)+ controller.prepare()+ controller.play()+ state.tree.markPlayed(mediaIds)+ screenManager.push(MusicCarPlaybackScreen(carContext, state))+ }++ private fun sectionedContent(tabId: String, label: String): Template {+ val tree = state.tree+ return SectionedItemTemplate.Builder()+ .addSection(+ RowSection.Builder()+ .setTitle(label)+ .setItems(songRows(tree.children(tabId)))+ .build(),+ )+ .build()+ }++ /** Condensed song rows: one line each so more fits on screen. */+ private fun songRows(items: List<MediaItem>): List<Row> =+ items.mapNotNull { item -> val meta = item.mediaMetadata val browsable = meta.isBrowsable == true val playable = !browsable && meta.isPlayable == true+ if (!browsable && !playable) return@mapNotNull null val row = Row.Builder() .setTitle(meta.title?.toString() ?: "Unknown") val subtitle = listOfNotNull(@@ -52,7 +202,7 @@ class MusicCarBrowseScreen( ).joinToString(" · ").takeIf { it.isNotBlank() } subtitle?.let { row.addText(it) } if (browsable) {- val count = tree.childCount(item.mediaId)+ val count = state.tree.childCount(item.mediaId) if (count > 0) row.addText("$count items") } row.setBrowsable(browsable)@@ -60,26 +210,91 @@ class MusicCarBrowseScreen( row.setOnClickListener { screenManager.push(MusicCarBrowseScreen(carContext, item.mediaId, state)) }- } else if (playable) {+ } else { row.setOnClickListener { play(item.mediaId) } }- list.addItem(row.build())+ row.build() }- val builder = ListTemplate.Builder()++ /** Single FAB: Play-all (media apps get max 1 on API 9+ hosts). */+ private fun playAllAction(): Action? {+ val items = state.tree.children(nodeId)+ if (items.none { it.mediaMetadata.isPlayable == true && it.mediaMetadata.isBrowsable != true }) {+ return null+ }+ return Action.Builder()+ .setTitle("Play")+ .setOnClickListener { playAll(items.map { it.mediaId }) }+ .build()+ }++ // ------------------------------------------------------------------+ // ListTemplate fallback (API 1–7)+ // ------------------------------------------------------------------++ private fun listContent(tabId: String, label: String): Template {+ val tree = state.tree+ val list = ItemList.Builder()+ for (item in tree.children(tabId)) {+ songRow(item)?.let { list.addItem(it) }+ }+ return ListTemplate.Builder() .setSingleList(list.build())- .setTitle(title)+ .setTitle(label) .setHeaderAction(Action.BACK)- if (items.any { it.mediaMetadata.isPlayable == true && it.mediaMetadata.isBrowsable != true }) {- builder.addAction(- Action.Builder()- .setTitle("Play")- .setOnClickListener { playAll(items.map { it.mediaId }) }+ .build()+ }++ private fun legacyListTemplate(): Template {+ val tree = state.tree+ val title = tree.item(nodeId)?.mediaMetadata?.title?.toString() ?: "Music"+ val items = tree.children(nodeId)+ val list = ItemList.Builder()+ if (nodeId != MusicLibraryTree.ROOT && items.isEmpty()) {+ list.addItem(+ Row.Builder()+ .setTitle("Loading…") .build(), ) }+ for (item in items) {+ songRow(item)?.let { list.addItem(it) }+ }+ val builder = ListTemplate.Builder()+ .setSingleList(list.build())+ .setTitle(title)+ .setHeaderAction(Action.BACK)+ playAllAction()?.let { builder.addAction(it) } return builder.build() } + private fun songRow(item: MediaItem): Row? {+ val meta = item.mediaMetadata+ val browsable = meta.isBrowsable == true+ val playable = !browsable && meta.isPlayable == true+ if (!browsable && !playable) return null+ val row = Row.Builder()+ .setTitle(meta.title?.toString() ?: "Unknown")+ val subtitle = listOfNotNull(+ meta.artist?.toString()?.takeIf { it.isNotBlank() },+ meta.albumTitle?.toString()?.takeIf { it.isNotBlank() },+ ).joinToString(" · ").takeIf { it.isNotBlank() }+ subtitle?.let { row.addText(it) }+ if (browsable) {+ val count = state.tree.childCount(item.mediaId)+ if (count > 0) row.addText("$count items")+ }+ row.setBrowsable(browsable)+ if (browsable) {+ row.setOnClickListener {+ screenManager.push(MusicCarBrowseScreen(carContext, item.mediaId, state))+ }+ } else {+ row.setOnClickListener { play(item.mediaId) }+ }+ return row.build()+ }+ private fun play(mediaId: String) { val playable = state.tree.resolveForPlayback(mediaId) ?: return val controller = state.controller ?: return