Search code examples
androidandroid-fragmentsandroid-architecture-navigation

Navigation Component .popBackStack() with arguments


I have Two fragment. SecondFragment and ThirdFragment. Actually I use the Navigation Component for passing value between fragments. Like this:

SecondFragment:

val action = SecondFragmentDirections.action_secondFragment_to_thirdFragment().setValue(1)

Navigation.findNavController(it).navigate(action)

Here is how I read the value from the ThirdFragment:

 arguments?.let {
           val args = ThirdFragmentArgs.fromBundle(it)
           thirdTextView.text = args.value.toString()
       }

It's work fine. Now my stack is look like this:

ThirdFragment

SecondFragment 

There is any option for pass value from the opened ThirdFragment to the previous SecondFragment with the new Navigation Component? (When ThirdFragment is finishing)

I know about onActivityResult, but If Nav.Component serve better solution than I want use that.

Thank you!


Solution

  • It's a bit late for this answer but someone may find it useful. In the updated versions of the navigation component library it is now possible to pass data while navigating back.

    Suppose the stack is like this

    FragmentA --> FragmentB.

    We are currently now in FragmentB and we want to pass data when we go back to FragmentA.

    Inside FragmentAwe can create an observer with a key:

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    val navController = findNavController()
    // Instead of String any types of data can be used
    navController.currentBackStackEntry?.savedStateHandle?.getLiveData<String>("key")
        ?.observe(viewLifecycleOwner) { 
    
        }
    }
    

    Then inside FragmentB if we change its value by accessing previous back stack entry it will be propagated to FragmentA and observer will be notified.

    val navController = findNavController()
    navController.previousBackStackEntry?.savedStateHandle?.set("key", "value that needs to be passed")
    navController.popBackStack()