From c72dff9971c66b28a2828c36a3b7932774e830b5 Mon Sep 17 00:00:00 2001 From: jhg3410 <80373033+jhg3410@users.noreply.github.com> Date: Thu, 23 Feb 2023 20:54:45 +0900 Subject: [PATCH] #8 - Integrate RallyTabRow with navigation --- .../example/compose/rally/RallyActivity.kt | 29 +++++++++++++++---- 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/NavigationCodelab/app/src/main/java/com/example/compose/rally/RallyActivity.kt b/NavigationCodelab/app/src/main/java/com/example/compose/rally/RallyActivity.kt index 60fad89..1e5ccb4 100644 --- a/NavigationCodelab/app/src/main/java/com/example/compose/rally/RallyActivity.kt +++ b/NavigationCodelab/app/src/main/java/com/example/compose/rally/RallyActivity.kt @@ -19,17 +19,16 @@ package com.example.compose.rally import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent -import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.padding import androidx.compose.material.Scaffold import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier +import androidx.navigation.NavGraph.Companion.findStartDestination +import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable +import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.rememberNavController import com.example.compose.rally.ui.components.RallyTabRow import com.example.compose.rally.ui.theme.RallyTheme @@ -50,13 +49,19 @@ class RallyActivity : ComponentActivity() { @Composable fun RallyApp() { RallyTheme { - var currentScreen: RallyDestination by remember { mutableStateOf(Overview) } val navController = rememberNavController() + + val currentBackStack by navController.currentBackStackEntryAsState() + val currentDestination = currentBackStack?.destination + + val currentScreen = rallyTabRowScreens.find { it.route == currentDestination?.route } ?: Overview Scaffold( topBar = { RallyTabRow( allScreens = rallyTabRowScreens, - onTabSelected = { screen -> currentScreen = screen }, + onTabSelected = { newScreen -> + navController.navigateSingleTopTo(newScreen.route) + }, currentScreen = currentScreen ) } @@ -79,3 +84,15 @@ fun RallyApp() { } } } + + +fun NavHostController.navigateSingleTopTo(route: String) = + this.navigate(route) { + popUpTo( + this@navigateSingleTopTo.graph.findStartDestination().id + ) { + saveState = true + } + launchSingleTop = true + restoreState = true + } \ No newline at end of file