Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ Examples showing how to use the layouts provided by the [Compose Material3 Adapt
- **[Animations](app/src/main/java/com/example/nav3recipes/animations)**: Shows how to override the default animations for all destinations and a single destination.

### Common use cases
- **[Common navigation UI](app/src/main/java/com/example/nav3recipes/commonui)**: A common navigation toolbar where each item in the toolbar navigates to a top level destination.
- **[Common navigation UI](app/src/main/java/com/example/nav3recipes/commonui)**: A common navigation toolbar where each item in the toolbar navigates to a top level destination.
- **[Multiple back stacks](app/src/main/java/com/example/nav3recipes/multiplestacks)**: Shows how to create multiple top level routes, each with its own back stack. Top level routes are displayed in a navigation bar allowing users to switch between them. State is retained for each top level route, and the navigation state persists config changes and process death.
- **[Conditional navigation](app/src/main/java/com/example/nav3recipes/conditional)**: Switch to a different navigation flow when a condition is met. For example, for authentication or first-time user onboarding.

### Architecture
Expand Down
4 changes: 4 additions & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,10 @@
android:name=".scenes.listdetail.ListDetailActivity"
android:exported="true"
android:theme="@style/Theme.Nav3Recipes"/>
<activity
android:name=".multiplestacks.MultipleStacksActivity"
android:exported="true"
android:theme="@style/Theme.Nav3Recipes"/>
</application>

</manifest>
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ import com.example.nav3recipes.dialog.DialogActivity
import com.example.nav3recipes.material.listdetail.MaterialListDetailActivity
import com.example.nav3recipes.material.supportingpane.MaterialSupportingPaneActivity
import com.example.nav3recipes.modular.hilt.ModularActivity
import com.example.nav3recipes.multiplestacks.MultipleStacksActivity
import com.example.nav3recipes.passingarguments.viewmodels.basic.BasicViewModelsActivity
import com.example.nav3recipes.passingarguments.viewmodels.hilt.HiltViewModelsActivity
import com.example.nav3recipes.passingarguments.viewmodels.koin.KoinViewModelsActivity
Expand Down Expand Up @@ -92,6 +93,7 @@ private val recipes = listOf(

Heading("Common use cases"),
Recipe("Common UI", CommonUiActivity::class.java),
Recipe("Multiple Stacks", MultipleStacksActivity::class.java),
Recipe("Conditional navigation", ConditionalActivity::class.java),

Heading("Architecture"),
Expand Down
108 changes: 108 additions & 0 deletions app/src/main/java/com/example/nav3recipes/multiplestacks/Content.kt
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") {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Button(onClick = onSubRouteClick) {
Text("Go to A1")
}
}
}
}
entry<RouteA1> {
ContentPink("Route A1") {
var count by rememberSaveable {
mutableIntStateOf(0)
}

Button(onClick = { count++ }) {
Text("Value: $count")
}
}
}
}

fun EntryProviderScope<NavKey>.featureBSection(
onSubRouteClick: (id: String) -> Unit,
) {
entry<RouteB> {
ContentGreen("Route B") {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Button(onClick = { onSubRouteClick("ABC") }) {
Text("Go to B1")
}
}
}
}
entry<RouteB1> {
ContentPurple("Route B1") {
var count by rememberSaveable {
mutableIntStateOf(0)
}
Button(onClick = { count++ }) {
Text("Value: $count")
}
}
}
}

fun EntryProviderScope<NavKey>.featureCSection(
onSubRouteClick: () -> Unit,
) {
entry<RouteC> {
ContentMauve("Route C") {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Button(onClick = onSubRouteClick) {
Text("Open sub route")
}
}
}
}
entry<RouteC1> {
ContentOrange("Route C1") {
var count by rememberSaveable {
mutableIntStateOf(0)
}

Button(onClick = { count++ }) {
Text("Value: $count")
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
/*
* 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.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.navigation3.runtime.NavKey
import androidx.navigation3.runtime.entryProvider
import androidx.navigation3.ui.NavDisplay
import com.example.nav3recipes.ui.setEdgeToEdgeConfig
import kotlinx.serialization.Serializable


@Serializable
data object RouteA : NavKey

@Serializable
data object RouteA1 : NavKey

@Serializable
data object RouteB : NavKey

@Serializable
data object RouteB1 : 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(onSubRouteClick = { id -> navigator.navigate(RouteB1) })
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)
)
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/*
* 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.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.runtime.toMutableStateList
import androidx.navigation3.runtime.NavBackStack
import androidx.navigation3.runtime.NavEntry
import androidx.navigation3.runtime.NavKey
import androidx.navigation3.runtime.rememberDecoratedNavEntries
import androidx.navigation3.runtime.rememberSaveableStateHolderNavEntryDecorator

/**
* 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
}
}

/**
* 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()
}
Loading