I am creating a simple project and I am using the navigation component. Here is what I am trying to achieve. I have a navigation graph and single activity that has FragmentContainerView that acts as NavHostFragment and NavigationView that displays the navigation drawer menu. From this activity, using the drawer menu item and navigation graph, I can navigate to a specific fragment. This fragment contains a bottom navigation view. How can I connect this bottom navigation to the activity's navigation to be able to press bottom navigation menu items and navigate to destinations in acitivity's navigation graph? I kind of did it with subgraphs: the destination had its own navigation graph, but this didn't work well, because after pressing the navigate back button, the user would navigate back to the start destination of this graph.
For now the solution I found is that,but the back button navigation still goes back to the starting destination(welcomeFragment in my case) instead of going back to the previous destination(TeamMainFragment),which I assume means that the destination navigated from bottom navigation is not added to the back stack.
@Override
public void onStart() {
super.onStart();
BottomNavigationView bottomNavigationView = binding.bottomNavigationView;
NavigationUI.setupWithNavController(bottomNavigationView,Navigation.findNavController(binding.getRoot()));
}
Is there any better solution?
I also tried this
NavHostFragment navHostFragment = (NavHostFragment) getParentFragment();
NavController navController = navHostFragment.getNavController();
BottomNavigationView bottomNavigationView = binding.bottomNavigationView;
NavigationUI.setupWithNavController(bottomNavigationView,navController);
Still not working as wanted: when I am in insertTeamFragment and press the navigate back button
it navigates back to welcomeFragment,instead of teamMainFragment.
Found a solution thanks to Adnan :
super.onStart();
NavHostFragment navHostFragment = (NavHostFragment) getParentFragment();
NavController navController = navHostFragment.getNavController();
BottomNavigationView bottomNavigationView = binding.bottomNavigationView;
bottomNavigationView.setOnNavigationItemSelectedListener(item -> {
navController.navigate(item.getItemId());
return true;
});
This works as wanted:when in insertTeamFragment and press the back navigate button it navigates back to teamMainFragment.But still don't understand why the NavigationUI solution is not working.If anyone knows,please comment.