7

When using the navigation architecture, is it possible to explicitly assign fragment tag names to the fragments that you navigate to so that later you can refer back to them if you need to do something with them on the back stack? I'm referring to navigate calls like these: NavController.navigate(R.id.exampleFragment)

If it's not possible, then what is the default tag name given to the fragments that NavController.navigate() adds to the back stack?

Raj Narayanan
  • 2,443
  • 4
  • 24
  • 43

1 Answers1

0

If you're using Navigation Component, should avoid using fragment related objects like tag, fragmentManager, findFragmentByTag/Id, setTargetFragment, ...

So you should use Navigation Component facilities like NavController, NavDestination, BackStackEntry and its SavedStateHandle.

To do something with them, you should find it in your back stack and set a value on its savedStateHandle:

For example A opens B and then B opens C, now C want pass something to A

// in C:
findNavController().getBackStackEntry(R.id.a)
         .savedStateHandle
         .set("Key","Value")


// in A: 
findNavController().getBackStackEntry(R.id.a)
         .savedStateHandle
         .get<String>("Key") // or getLiveData<String>("Key").observe(...)

At the end:

What is the default tag name given to the fragments that NavController.navigate() adds to the back stack?

It doesn't use fragments tag. So all fragments tag are null

beigirad
  • 4,986
  • 2
  • 29
  • 52