I have a Comparator Screen which is a Fragment that is splitted into 2 sub-screens. Before using Navigation Component I could easily just:
private void initializeFragments() {
FoodComparatorFragment comparatorFragment1 = new FoodComparatorFragment();
FoodComparatorFragment comparatorFragment2 = new FoodComparatorFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.comparator_fragment_1, comparatorFragment1);
transaction.add(R.id.comparator_fragment_2, comparatorFragment2);
transaction.commit();
}
However, I don't know how I should perform this operation with the Navigation Component WITHOUT using explicitly the FragmentManager.
By default with navigation components there is one
NavHostFragmenthosted by the main activity for one activity/many fragments model. For many activities/fragments model, each activity has its ownNavHostFragment/NavGraph.Here we'll consider one activity, many fragments model, where one of these fragments is the Comparator Screen (parent fragment) that is splitted into 2 sub-screens/fragments.
But the
NavHostFragmentcan only host a single fragment at a time; so the idea here is to have twoNavHostFragmentswithin the comparator/parent fragment.Considering the below example:
MainActivitythat hosts two fragments (HomeFragment,ParentFragment).ParentFragmentis the comparator with twoNavHostFragments, each can host a single fragment; the top one isTopFragment, the bottom isBottomFragment.HomeFragmentto theParentFragmentintargument sent to each sub-screen, the Top/Bottom fragments, done by sending arguments to the sub-screens along with the action from theHomeFragmentto theParentFragment; they will be displayed onTextViewson the screen.Now we have 3 NavGraphs:
Main (mobile_navigation.xml):
And in
ParentFragment, another twoNavGraphs, each for a sub-screen:For the 1st sub-screen (top_navigation.xml):
For the 2nd sub-screen (bottom_navigation.xml):
Layouts:
activity_main.xml
fragment_parent.xml
fragment_top/bottom.xml are straightforward
fragment_top.xml:
The
NavGraphof the Top & Bottom fragments will be set programmatically in order to allow passing the arguments from the mainNavGraphto the sub-screens'NavGraphs.Now in the
HomeFragment, there is a button to go to theParentFragmentwith the action defined in theNavGraph, which sends the arguments needed for both sub-screens:Then receive the arguments at the
ParentFragmentwith theSafeArgs:Once more at the destination top/bottom sub-screens, get the argument with
safeArgs, and set it to theTextView: