androidandroid-fragmentsviewmodelandroid-navigationfragmentmanager

Communicate from ChildFragment to Parent when parent button's onClick


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.


Solution

  • 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...