0

I've got some problems understanding Fragments in Android.

The bottom navigation of my MainActivity has got three items: FragmentA, FragmentB, FragmentC.

FragmentC has got a button. When the user clicks that button, another FragmentD should display additional information.

  • FragmentD should have an up-button in the toolbar. When the user clicks on that button, he gets back to FragmentC.
  • When the user selects a different fragment from the navigation, FragmentD should disappear.

Inside the onClick of my button I've tried to use this

FragmentManager manager = requireActivity().getSupportFragmentManager();
                FragmentTransaction transaction = manager.beginTransaction();
                transaction.replace(R.id.nav_host_fragment, new FragmentD());
                transaction.addToBackStack(null);
                transaction.commit();

with nav_host_fragment being the fragment container for the bottom navigation items of my MainActivity.

  • Why doesn't transaction.replace replace FragmentC with FragmentD? When I press the button, FragmentD appears above FragmentC and has got a transparent background. FragmentD also does not get replaced by the other fragments when I select a different item from the bottom navigation. Is it because I'm using the nav_host_fragment container for FragmentD?
  • How do I get the up-button?
  • 1
    Why are you trying to do a FragmentTransaction at all when you're using Navigation? Is there a reason you're not just [navigating to a destination](https://developer.android.com/guide/navigation/navigation-navigate)? – ianhanniballake Mar 06 '20 at 18:16
  • Thanks @ian, that has helped a lot. In the Navigation xml file I've added FragmentD and an action for FragmentC with FragmentD as destination. In the button's onClick I now call Navigation.findNavController(view).navigate(R.id.fragment_c_to_fragment_d); The only thing that doesn't work is the up button in the toolbar. Do you know how I can make it work? It's there but it doesn't work. –  Mar 06 '20 at 19:13
  • Found it. I have to override onSupportNavigateUp: @Override public boolean onSupportNavigateUp() { return Navigation.findNavController(this, R.id.main_fragment).navigateUp() || super.onSupportNavigateUp(); } –  Mar 06 '20 at 19:27

1 Answers1

0

The solution is to use Navigation instead of FragmentTransaction.

In the Navigation xml file I've added FragmentD and an action for FragmentC with FragmentD as destination. In the button's onClick I now call Navigation.findNavController(view).navigate(R.id.fragment_c_to_fragment_d);

To make the button work, I had to override onSupportNavigateUp:

@Override public boolean onSupportNavigateUp() { return Navigation.findNavController(this, R.id.main_fragment).navigateUp() || super.onSupportNavigateUp(); }