Communicate from ChildFragment to Parent when parent button's onClick
Asked Answered
C

1

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.

Convertible answered 5/7, 2021 at 11:8 Comment(1)
Consider using an event bus. greenrobot.org/eventbusBinnie
C
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...
Convertible answered 26/7, 2021 at 14:56 Comment(2)
also have a look at my questions #70721718 and #70680827Hillary
your solutions works as there is another NavHost Fragment between parent and childFragmentHillary

© 2022 - 2024 — McMap. All rights reserved.