-
Notifications
You must be signed in to change notification settings - Fork 72
Add multiple back stacks recipe #121
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 12 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
57b4af6
Refactor: Introduce Navigator for multiple back stacks
dturner 91877ad
Remove unused imports
dturner 364d45a
Update README for multiple back stacks recipe
dturner f1335bb
Update app/src/main/java/com/example/nav3recipes/commonui/CommonUiAct…
dturner f7b83c7
Update app/src/main/java/com/example/nav3recipes/commonui/Navigator.kt
dturner e25b93f
Refactor Navigator to be more testable and fix navigation bug
dturner 595de4d
feat: Add multiple stacks recipe
dturner 0d776d4
feat: Add multiple stacks recipe
dturner db11414
Refactor Navigator to remove `topLevelRoutes`
dturner e46ff3a
Refactor MultipleStacks to use built-in state management
dturner 5536aba
Update README.md
dturner 8cc344f
Fix: Correct description for Common UI recipe
dturner 5fbc0ba
Refactor multiple backstacks implementation
dturner File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
108 changes: 108 additions & 0 deletions
108
app/src/main/java/com/example/nav3recipes/multiplestacks/Content.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,108 @@ | ||
| /* | ||
| * 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 com.example.nav3recipes.multiplestacks | ||
|
|
||
| import androidx.compose.foundation.layout.Column | ||
| import androidx.compose.material3.Button | ||
| import androidx.compose.material3.Text | ||
| import androidx.compose.runtime.getValue | ||
| import androidx.compose.runtime.mutableIntStateOf | ||
| import androidx.compose.runtime.saveable.rememberSaveable | ||
| import androidx.compose.runtime.setValue | ||
| import androidx.compose.ui.Alignment | ||
| import androidx.navigation3.runtime.EntryProviderScope | ||
| import androidx.navigation3.runtime.NavKey | ||
| import com.example.nav3recipes.content.ContentGreen | ||
| import com.example.nav3recipes.content.ContentMauve | ||
| import com.example.nav3recipes.content.ContentOrange | ||
| import com.example.nav3recipes.content.ContentPink | ||
| import com.example.nav3recipes.content.ContentPurple | ||
| import com.example.nav3recipes.content.ContentRed | ||
|
|
||
| fun EntryProviderScope<NavKey>.featureASection( | ||
| onSubRouteClick: () -> Unit, | ||
| ) { | ||
| entry<RouteA> { | ||
| ContentRed("Route A title") { | ||
| Column(horizontalAlignment = Alignment.CenterHorizontally) { | ||
| Button(onClick = onSubRouteClick) { | ||
| Text("Go to A1") | ||
| } | ||
| } | ||
| } | ||
| } | ||
| entry<RouteA1> { | ||
| ContentPink("Route A1 title") { | ||
| var count by rememberSaveable { | ||
| mutableIntStateOf(0) | ||
| } | ||
|
|
||
| Button(onClick = { count++ }) { | ||
| Text("Value: $count") | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| fun EntryProviderScope<NavKey>.featureBSection( | ||
| onDetailClick: (id: String) -> Unit, | ||
| ) { | ||
| entry<RouteB> { | ||
| ContentGreen("Route B title") { | ||
| Column(horizontalAlignment = Alignment.CenterHorizontally) { | ||
| Button(onClick = { onDetailClick("ABC") }) { | ||
| Text("Go to B1") | ||
| } | ||
| } | ||
| } | ||
| } | ||
| entry<RouteB1> { key -> | ||
| ContentPurple("Route B1 title. ID: ${key.id}") { | ||
| var count by rememberSaveable { | ||
| mutableIntStateOf(0) | ||
| } | ||
| Button(onClick = { count++ }) { | ||
| Text("Value: $count") | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| fun EntryProviderScope<NavKey>.featureCSection( | ||
| onSubRouteClick: () -> Unit, | ||
| ) { | ||
| entry<RouteC> { | ||
| ContentMauve("Route C title") { | ||
| Column(horizontalAlignment = Alignment.CenterHorizontally) { | ||
| Button(onClick = onSubRouteClick) { | ||
| Text("Open sub route") | ||
| } | ||
| } | ||
| } | ||
| } | ||
| entry<RouteC1> { | ||
| ContentOrange("Route C1 title") { | ||
| var count by rememberSaveable { | ||
| mutableIntStateOf(0) | ||
| } | ||
|
|
||
| Button(onClick = { count++ }) { | ||
| Text("Value: $count") | ||
| } | ||
| } | ||
| } | ||
| } |
228 changes: 228 additions & 0 deletions
228
app/src/main/java/com/example/nav3recipes/multiplestacks/MultipleStacksActivity.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,228 @@ | ||
| /* | ||
| * 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 com.example.nav3recipes.multiplestacks | ||
|
|
||
| import android.os.Bundle | ||
| import androidx.activity.ComponentActivity | ||
| import androidx.activity.compose.setContent | ||
| import androidx.compose.foundation.layout.padding | ||
| import androidx.compose.material.icons.Icons | ||
| import androidx.compose.material.icons.filled.Camera | ||
| import androidx.compose.material.icons.filled.Face | ||
| import androidx.compose.material.icons.filled.Home | ||
| import androidx.compose.material3.Icon | ||
| import androidx.compose.material3.NavigationBar | ||
| import androidx.compose.material3.NavigationBarItem | ||
| import androidx.compose.material3.Scaffold | ||
| import androidx.compose.material3.Text | ||
| import androidx.compose.runtime.Composable | ||
| import androidx.compose.runtime.MutableState | ||
| import androidx.compose.runtime.getValue | ||
| import androidx.compose.runtime.mutableStateOf | ||
| import androidx.compose.runtime.remember | ||
| import androidx.compose.runtime.saveable.rememberSerializable | ||
| import androidx.compose.runtime.setValue | ||
| import androidx.compose.runtime.snapshots.SnapshotStateList | ||
| import androidx.compose.runtime.toMutableStateList | ||
| import androidx.compose.ui.Modifier | ||
| import androidx.compose.ui.graphics.vector.ImageVector | ||
| import androidx.navigation3.runtime.NavBackStack | ||
| import androidx.navigation3.runtime.NavEntry | ||
| import androidx.navigation3.runtime.NavKey | ||
| import androidx.navigation3.runtime.entryProvider | ||
| import androidx.navigation3.runtime.rememberDecoratedNavEntries | ||
| import androidx.navigation3.runtime.rememberNavBackStack | ||
| import androidx.navigation3.runtime.rememberSaveableStateHolderNavEntryDecorator | ||
| import androidx.navigation3.runtime.serialization.NavKeySerializer | ||
| import androidx.navigation3.ui.NavDisplay | ||
| import androidx.savedstate.compose.serialization.serializers.MutableStateSerializer | ||
| import com.example.nav3recipes.ui.setEdgeToEdgeConfig | ||
| import kotlinx.serialization.Serializable | ||
| import kotlin.collections.last | ||
|
|
||
|
|
||
| @Serializable | ||
| data object RouteA : NavKey | ||
|
|
||
| @Serializable | ||
| data object RouteA1 : NavKey | ||
|
|
||
| @Serializable | ||
| data object RouteB : NavKey | ||
|
|
||
| @Serializable | ||
| data class RouteB1(val id: String) : NavKey | ||
|
|
||
| @Serializable | ||
| data object RouteC : NavKey | ||
|
|
||
| @Serializable | ||
| data object RouteC1 : NavKey | ||
|
|
||
| private val TOP_LEVEL_ROUTES = mapOf<NavKey, NavBarItem>( | ||
| RouteA to NavBarItem(icon = Icons.Default.Home, description = "Route A"), | ||
| RouteB to NavBarItem(icon = Icons.Default.Face, description = "Route B"), | ||
| RouteC to NavBarItem(icon = Icons.Default.Camera, description = "Route C"), | ||
| ) | ||
|
|
||
| data class NavBarItem( | ||
| val icon: ImageVector, | ||
| val description: String | ||
| ) | ||
|
|
||
| class MultipleStacksActivity : ComponentActivity() { | ||
| override fun onCreate(savedInstanceState: Bundle?) { | ||
| setEdgeToEdgeConfig() | ||
| super.onCreate(savedInstanceState) | ||
| setContent { | ||
| val navigationState = rememberNavigationState( | ||
| startRoute = RouteA, | ||
| topLevelRoutes = TOP_LEVEL_ROUTES.keys | ||
| ) | ||
|
|
||
| val navigator = remember { Navigator(navigationState) } | ||
|
|
||
| val entryProvider = entryProvider { | ||
| featureASection(onSubRouteClick = { navigator.navigate(RouteA1) }) | ||
| featureBSection(onDetailClick = { id -> navigator.navigate(RouteB1(id)) }) | ||
| featureCSection(onSubRouteClick = { navigator.navigate(RouteC1) }) | ||
| } | ||
|
|
||
| Scaffold(bottomBar = { | ||
| NavigationBar { | ||
| TOP_LEVEL_ROUTES.forEach { (key, value) -> | ||
| val isSelected = key == navigationState.topLevelRoute | ||
| NavigationBarItem( | ||
| selected = isSelected, | ||
| onClick = { navigator.navigate(key) }, | ||
| icon = { | ||
| Icon( | ||
| imageVector = value.icon, | ||
| contentDescription = value.description | ||
| ) | ||
| }, | ||
| label = { Text(value.description) } | ||
| ) | ||
| } | ||
| } | ||
| }) { paddingValues -> | ||
| NavDisplay( | ||
| entries = navigationState.toEntries(entryProvider), | ||
| onBack = { navigator.goBack() }, | ||
| modifier = Modifier.padding(paddingValues) | ||
| ) | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Convert NavigationState into NavEntries. | ||
| */ | ||
| @Composable | ||
| fun NavigationState.toEntries( | ||
| entryProvider: (NavKey) -> NavEntry<NavKey> | ||
| ): SnapshotStateList<NavEntry<NavKey>> { | ||
|
|
||
| val decoratedEntries = backStacks.mapValues { (_, stack) -> | ||
| val decorators = listOf( | ||
| rememberSaveableStateHolderNavEntryDecorator<NavKey>(), | ||
| ) | ||
| rememberDecoratedNavEntries( | ||
| backStack = stack, | ||
| entryDecorators = decorators, | ||
| entryProvider = entryProvider | ||
| ) | ||
| } | ||
|
|
||
| return stacksInUse | ||
| .flatMap { decoratedEntries[it] ?: emptyList() } | ||
| .toMutableStateList() | ||
| } | ||
|
|
||
| /** | ||
| * Handles navigation events (forward and back) by updating the navigation state. | ||
| */ | ||
| class Navigator(val state: NavigationState){ | ||
| fun navigate(route: NavKey){ | ||
| if (route in state.backStacks.keys){ | ||
| // This is a top level route, just switch to it | ||
| state.topLevelRoute = route | ||
| } else { | ||
| state.backStacks[state.topLevelRoute]?.add(route) | ||
| } | ||
| } | ||
|
|
||
| fun goBack(){ | ||
|
|
||
| val currentStack = state.backStacks[state.topLevelRoute] ?: | ||
| error("Stack for $state.topLevelRoute not found") | ||
| val currentRoute = currentStack.last() | ||
|
|
||
| // If we're at the base of the current route, go back to the start route stack. | ||
| if (currentRoute == state.topLevelRoute){ | ||
| state.topLevelRoute = state.startRoute | ||
| } else { | ||
| currentStack.removeLast() | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Create a navigation state that persists config changes and process death. | ||
| */ | ||
| @Composable | ||
| fun rememberNavigationState( | ||
| startRoute: NavKey, | ||
| topLevelRoutes: Set<NavKey> | ||
| ) : NavigationState { | ||
|
|
||
| val topLevelRoute = rememberSerializable( | ||
| serializer = MutableStateSerializer(NavKeySerializer()) | ||
| ){ | ||
| mutableStateOf(startRoute) | ||
| } | ||
|
|
||
| return NavigationState( | ||
| topLevelRoute = topLevelRoute, | ||
| backStacks = topLevelRoutes.associateWith { key -> | ||
| rememberNavBackStack(key) | ||
| } | ||
| ) | ||
| } | ||
|
|
||
| /** | ||
| * State holder for navigation state. | ||
| * | ||
| * @param topLevelRoute - the current top level route | ||
| * @param backStacks - the back stacks for each top level route | ||
| */ | ||
| class NavigationState( | ||
| topLevelRoute: MutableState<NavKey>, | ||
| val backStacks: Map<NavKey, NavBackStack<NavKey>> | ||
| ) { | ||
| val startRoute = topLevelRoute.value | ||
| var topLevelRoute : NavKey by topLevelRoute | ||
| val stacksInUse : List<NavKey> | ||
| get(){ | ||
| val stacksInUse = mutableListOf(startRoute) | ||
| if ([email protected] != startRoute) stacksInUse += [email protected] | ||
| return stacksInUse | ||
| } | ||
| } | ||
|
|
||
|
|
||
20 changes: 20 additions & 0 deletions
20
app/src/main/java/com/example/nav3recipes/multiplestacks/README.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| # Multiple back stacks recipe # | ||
|
|
||
| This recipe demonstrates how to create multiple back stacks. | ||
|
|
||
| The app has three top level routes: `RouteA`, `RouteB` and `RouteC`. These routes have sub routes `RouteA1`, `RouteB1` and `RouteC1` respectively. The content for the sub routes is a counter that can be used to verify state retention through configuration changes and process death. | ||
|
|
||
| The app's navigation state is held in the `NavigationState` class. The state itself is created using `rememberNavigationState`. | ||
|
|
||
| Navigation events are handled by the `Navigator`. It updates the navigation state. | ||
|
|
||
| The navigation state is converted into `NavEntry`s with `NavigationState.toEntries`. These entries are then displayed by `NavDisplay`. | ||
|
|
||
| Key behaviors: | ||
|
|
||
| - This app follows the "exit through home" pattern where the user always exits through the starting back stack. This means that `RouteA`'s entries are _always_ in the list of entries. | ||
| - Navigating to a top level route that is not the starting route _replaces_ the other entries. For example, navigating A->B->C would result in entries for A+C, B's entries are removed. | ||
|
|
||
| Important implementation details: | ||
|
|
||
| - Each top level route has its own `SaveableStateHolderNavEntryDecorator`. This is the object responsible for managing the state for the entries in its back stack. |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.