androidkotlinnavigationandroid-jetpack-composedialog

jetpack compose overlapping screens


in Android jetpack compose I must navigate to a screen with its view model and state. I don't want to use dialog, because it makes my architecture complicated

so how to navigate from the first screen to the second screen, which overlaps on top of the first Screen, not replacing it?

this is what chatGPT gives me. but it is not working

@Composable
fun FirstScreen(navController: NavController) {
    Column {
        Text(text = "This is the first screen")
        Button(onClick = { navController.navigate("second") }) {
            Text(text = "Go to second screen")
        }
    }
}

@Composable
fun SecondScreen(navController: NavController) {
    Dialog(onDismissRequest = { navController.popBackStack() }) {
        Text(text = "This is the second screen")
    }
}

@Composable
fun MyApp() {
    val navController = rememberNavController()
    NavHost(navController = navController, startDestination = "first") {
        composable("first") { FirstScreen(navController) }
        composable("second") { SecondScreen(navController) }
    }
}

Solution

  • you can use dialog instead of composable in NavHost

    this is the code in the current example

    @Preview
    @Composable
    fun MyApp() {
        val navController = rememberNavController()
        NavHost(navController = navController, startDestination = "first") {
            composable("first") { FirstScreen(navController) }
            dialog("second") { SecondScreen(navController) }
        }
    }
    
    @Composable
    fun FirstScreen(navController: NavController) {
        Column(
            Modifier
                .fillMaxSize()
                .background(Color.Blue), verticalArrangement = Arrangement.Center,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Text(text = "This is the first screen")
            Button(onClick = { navController.navigate("second") }) {
                Text(text = "Go to second screen")
            }
        }
    }
    
    @Composable
    fun SecondScreen(navController: NavController) {
        Column(Modifier.background(Color.Red.copy(alpha = 0.1f))) {
            Text(text = "This is the second screen")
            Button(onClick = { navController.popBackStack() }) {
                Text(text = "Go back")
            }
        }
    }