1

Hi I am new to android NavigationManager.

Consider fragments A, B and C conected in nav_graph as shown in the picture. scheme

Basically what I am trying to achieve is to navigate from fragment A directly to C. But when clicking on back button, I want it to behave as if I were first in fragment B.

So A->C, on back buttons: C->B->A

Is there some way, how I could add fragment B to backstack without actually showing it using NavigationManager?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Yoda066
  • 304
  • 6
  • 11
  • checkout my old [answer](https://stackoverflow.com/a/56270422/6376080) on this type question. – Nick Bapu May 28 '19 at 10:38
  • @NickBapu Thanks, but I was trying to do it without overwriting onBack method. That's why I specifically asked for solution using NavigationManager. – Yoda066 May 28 '19 at 10:43
  • Look this answer https://stackoverflow.com/questions/12854105/custom-back-stack-for-each-fragment-in-tabhost-in-android – Sai Jayant May 28 '19 at 10:57

1 Answers1

2

So it seems I should be more careful when reading documentation. I missed this site.

There is mechanism for custom back behavior. All I needed to do was to add this code to fragment C class:

//use onResume if you want to handle orientation change
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    val callback = requireActivity().onBackPressedDispatcher.addCallback(this, object :
        OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
            val options = NavOptions.Builder()
                .setPopUpTo(R.id.fragmentC, true)
                .build()

            navController.navigate(R.id.fragmentB, options)
        }
    })
}

My mindset was wrong the whole time. I was trying to add B to backstack when launching C. What I had to do instead in fragment C on back button pressed was going forward to B and delete C from backstack.

Yoda066
  • 304
  • 6
  • 11