Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Android Navigation Architecture, how can I check if current Fragment is the last one?

I need to display custom AlertDialog, but only when there are no more fragments after calling NavController.navigateUp(). My current code does something similar, but there is a bug to it:

override fun onBackPressed() {

    if (navController.navigateUp()) {
        return
    }

    showQuitDialog()
}

This somewhat works, but if I cancel the AlertDialog and don't quit the app, navController already navigated up to NavGraph root, which is not the fragment in which I was when AlertDialog appeared. So, if I try to use any navigation action from that fragment, I get error:

java.lang.IllegalArgumentException: navigation destination com.example.test/actionNavigateToNextFragment is unknown to this NavController

This could be resolved, if I had access to mBackStack field in NavController, but it's package private, and I can't use reflection in my current project. But if it was public, I would use it the following way:

override fun onBackPressed() {

    // 2 because first one is NavGraph, second one is last fragment on the stack
    if(navController.mBackStack.size > 2) { 
        navController.navigateUp()
        return
    }

    showQuitDialog()
}

Is there a way to do this without reflection?

like image 395
xinaiz Avatar asked Aug 31 '18 08:08

xinaiz


2 Answers

You can compare the ID of the start destination with the ID of the current destination. Something like:

override fun onBackPressed() = when {
    navController.graph.startDestination == navController.currentDestination?.id -> showQuitDialog()
    else -> super.onBackPressed()
}

Hope it helps.

like image 76
Marcelo Esperidiao Avatar answered Oct 10 '22 07:10

Marcelo Esperidiao


Try this for any destination (you can find your destination id in the navigation graph):

private fun isDesiredDestination(): Boolean {
    return with(navController) {
        currentDestination == graph[R.id.yourDestinationId]
    }
}
like image 39
Manzur Alahi Avatar answered Oct 10 '22 05:10

Manzur Alahi