While running the following app:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
TestsComposeTheme {
val navController: NavHostController = rememberNavController()
Scaffold { innerPadding ->
NavHost(
navController = navController,
startDestination = NUM.ONE.name,
modifier = Modifier.padding(innerPadding)
) {
composable(route = NUM.ONE.name) {
Column {
Text(
text = "1"
)
Button(
onClick = { navController.navigate(NUM.TWO.name) }
) { Text("Next") }
}
}
composable(route = NUM.TWO.name) {
Column {
Text(
text = "2"
)
Button(
onClick = { navController.navigate(NUM.THREE.name) }
) { Text("Next") }
}
}
composable(route = NUM.THREE.name) {
Column {
Text(
text = "3"
)
}
}
}
}
}
}
}
}
enum class NUM {
ONE, TWO, THREE
}
If i navigate to page three, and then press the back button twice and click "next" quickly from page one, it skips page two and goes straight to page three. if i wait a second before clicking "next" from page one, it goes to page two as expected.
I can't seem to figure out why it does that. your help would be greatly appreciated!
I'm trying to go through the "Android Basics with Compose" course on android.com. for some reason the navigation works properly on the apps that they use as examples.
You actually click the button from the second page, not the first page. The reason is that, by default, the navigation includes an exit animation of the current composable and an enter animation for the the new composable. By default that are fade-out/fade-in animations that take 700ms each. If you are quick (0.7s) you can still click the button from the page you are in the process to navigate away from.
You actually click the button from the second page while it is in the process of fading out to make place for the first page. Since you click the button from the second page (and not the one on the first page) you will navigate to the third page (not the second).
In your example the buttons from the first and second page look the same and are placed at the same location, so they cannot be distinguished and you won't notice the animations. However, if you place the buttons at different locations it becomes obvious that there are two different buttons involved, and clicking the first always brings you to the second page, while clicking the second always navigates to the third page.
In a real app this usually won't be an issue because the different screens will look different enough so the user won't confuse an element from one page with an element from the next. You can also choose other animations, like slide-in/slide-out animations that are much more obvious, and you can even disable them entirely.