0

Let's say I have 4 fragments and navigate through them in the order A -> B -> C -> D using a NavController object.

A is my home screen.

I'd like to write a single function called goToA() that can be inherited and called from either B, C or D which navigates to A and clears up the back stack

How do I go about that?

Kun.tito
  • 165
  • 1
  • 7
  • 1
    You could create a Global Action (https://developer.android.com/guide/navigation/navigation-global-action) that uses `popUpTo` to navigate to `A` and pop everything but that off the back stack (https://developer.android.com/guide/navigation/navigation-navigate#pop) – cactustictacs Jun 14 '22 at 17:00

2 Answers2

0

In your BaseFragment just create the function:

protected fun goToA() {
    findNavController().popBackStack(R.id.<id of fragment A in the nav graph here>, false)
}

Now you can call this function from either B, C or D

Nongthonbam Tonthoi
  • 12,667
  • 7
  • 37
  • 64
  • FWIW, just an opinion. https://levelup.gitconnected.com/android-nightmares-base-classes-ccf55dbd0604 https://proandroiddev.com/say-no-to-baseactivity-and-basefragment-83b156ed8998 – Tenfour04 Jun 14 '22 at 13:13
0

You can write an extension function for it, defined at the top level outside any classes, that you can call from any of your Fragments:

fun Fragment.goToA() {
    //...
}
Tenfour04
  • 83,111
  • 11
  • 94
  • 154