1

I have a parent Fragment that has inside a FragementContainerView in which there is a transition of different Fragments. The parentFragment has a button that when is clicked it has to collect all the data from the different children fragments inside the container view. I am using Navigation component and FragmentResultAPI, the first for the fragment navigation/transition and the last for getting the results from the children to the parent. I know how to return back the data from the children to the parent, but I do not know how to notify the children to send the data back. I've found this:

View view = inflater.inflate(R.layout.parent_fragment, container, false);
MyFirstChildFragment fragment = (MyFirstChildFragment) getChildFragmentManager().findFragmentById(R.id.child_fragment_id);
fragment.heyChildrenGiveMeYourDataBack(); //on Button click listener

I know this is the traditional way, but I was wondering there was a more modern way or, let's call it, a Navigation way.

The parent fragment belongs to the main_graph_nav but all children belong to a different nested_graph_nav. So I have a scoped ViewModel to share the data between the children but still no idea how to notice the children to send the data back to the parent.

mantc_sdr
  • 451
  • 3
  • 17

1 Answers1

2

I finally decided to search the FragmentManager of the parent in the child's code in order to set the Fragment result by calling:

getParentFragment().getParentFragmentManager().setFragmentResult...

and inside the parent's code get the result by:

getChildFragmentManager().setFragmentResultListener...
mantc_sdr
  • 451
  • 3
  • 17
  • also have a look at my questions https://stackoverflow.com/questions/70721218/receive-fragment-result-in-navigation-component-fragment and https://stackoverflow.com/questions/70680327/toolbar-icon-handling-using-navigation-component – Taimoor Khan Jan 16 '22 at 07:27
  • your solutions works as there is another NavHost Fragment between parent and childFragment – Taimoor Khan Jan 16 '22 at 07:32