Search code examples
androidkotlinandroid-jetpack-composeandroid-jetpack-navigationandroid-jetpack-compose-material3

Jetpack Compose Navigation by keeping TopBar and NavBar fixed


I have seperate function for TopAppBar and Naigation_bar in jetpack compose how to fix these at their position and on click of Navigation_Bar item the navigation should happen that will change the main contents of the screen keeping TopAppBar and Naigation_bar fix at their position. Currently OnClick I'm navigating to new screen every time but now I want that the screen should be same but only the content will change based on clicks.

Scaffold( topBar = { TopBar() }, content = {

            Row(
                modifier = Modifier
                    .background(color = Color.White)
            ) {
                NavigationBar(
                    modifier = Modifier

                        .weight(.2f),
                    navController = navController
                )
                Spacer(modifier = Modifier.width(16.dp))
                Drawer(
                    modifier = Modifier
                        .weight(.2f)
                    navController = navController,
                )

                Box(
                    modifier = Modifier.weight(.6f)

                ) {
                    Column(
                        modifier = Modifier
                            .fillMaxSize()
                            .padding(16.dp),
                        verticalArrangement = Arrangement.Top,
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        
                        ContentScreen(modifier = Modifier)

                    }
                }

            }
        }
    ) I'm using this for every screens but now I want that the screen should be same but only the content will change based on clicks.

Solution

  • A single componant should handle all of your componants. Use a NavHost to control the navigation

    basic example

    @Composable
    fun MainScreen(navController: NavHostController) {
        Scaffold(
            topBar = { TopBar() },
            bottomBar = { NavigationBar(navController = navController) }
        ) { paddingValues ->
            NavHost(
                navController = navController,
                startDestination = "home",
                modifier = Modifier.padding(paddingValues)
            ) {
                composable("home") { HomeContent() }
                composable("Page one") { ProfileContent() }
                composable("Page Two") { SettingsContent() }
                // more
            }
        }
    }