I was testing Compose and navigation and noticed strange behavior (nav ver: androidx.navigation:navigation-compose:2.4.0-alpha10)
In this example, is a screen to check if the app is up to date or not (boolean var in the code for simple test), and if yes, navigate to other screen.
The big issue I found here was that when automating the navigation, the second screen switches to the first one very quickly. But if the navigation is done with the click of a button, for example, nothing strange happens...
MainActivity file code:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
AppTheme {
Surface(color = MaterialTheme.colors.background) {
val navController = rememberNavController()
NavHost(
navController = navController,
startDestination = "first_screen"
) {
composable(route = "first_screen") {
FirstScreen(navController)
}
composable(route = "second_screen") {
SecondScreen(navController)
}
}
}
}
}
}
}
FirstScreen file code:
@Composable
fun FirstScreen(navController: NavController) {
val isAppUpdated = true // switch case
Scaffold(
topBar = {
TopAppBar {
Text(text = "First Screen Bar")
}
}
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier.fillMaxSize()
) {
Text(
text = "First Screen",
textAlign = TextAlign.Center,
style = MaterialTheme.typography.h4
)
if (!isAppUpdated) OutdatedApp()
else {
// Two options to navigate: with compose button or automatically
// UpdatedApp {
// navigateToSecondScreen(navController)
// }
navigateToSecondScreen(navController)
}
}
}
}
@Composable
fun OutdatedApp() {
Text(
text = "Your app is out of date, consider updating it!",
textAlign = TextAlign.Center,
style = MaterialTheme.typography.body1
)
}
@Composable
fun UpdatedApp(onClick: () -> Unit) {
Button(
onClick = { onClick() }
) {
Text(
text = "Navigate to Second Screen",
style = MaterialTheme.typography.button
)
}
}
private fun navigateToSecondScreen(navController: NavController) {
navController.navigate(route = "second_screen") {
launchSingleTop
popUpTo(route = "first_screen") { inclusive = true }
}
}
SecondScreen file code:
@Composable
fun SecondScreen(navController: NavController) {
Scaffold(
topBar = {
TopAppBar {
Text(text = "Second Screen Bar")
}
}
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier.fillMaxSize()
) {
Text(
text = "Second Screen",
textAlign = TextAlign.Center,
style = MaterialTheme.typography.h4
)
}
}
}
Can anyone explain what happens in these cases?
And any solution to implement this logic?
EDIT
I did another test without Scaffold on FirstScreen and it looks like this problem didn't happen...