F.M.
F.M.

Reputation: 285

Android conditional remove fragment from back-stack using Navigation Components

In an Android APP I have the following navigation using Navigation Components and Nav Graph:

Fragment A -> Fragment B -> Fragment C -> Fragment D -> Fragment E

Anyway the back navigation must be customized:

Fragment A <- Fragment B <- Fragment C <- Fragment D

Fragment A <- Fragment E

I can set app:popUpTo and app:popUpToInclusive directly in xml Nav Graph only for actionDtoE, becouse the "removing" from back-stack of Fragment B and Fragment C must be conditional, only if I reach Fragment E.

How can I do this conditional remove of fragment from back-stack using Navigation Components?

Upvotes: 0

Views: 30

Answers (1)

Celil Uysal
Celil Uysal

Reputation: 53

You can override FragmentD back action using onBackPressed in activiy or using callbacks in fragment. In my case I used activity.

Fragment A <- Fragment E

   override fun onBackPressed() {
        if (navController.currentDestination?.id == R.id.EFragment && condition) {
            navController.popBackStack(R.id.aFragment, false)
            return
        }
        super.onBackPressed()
    }

Other variations:

Fragment A <- Fragment E => navController.popBackStack(R.id.aFragment, true)

Fragment B <- Fragment E => navController.popBackStack(R.id.bFragment, false)

Upvotes: 0

Related Questions