0

I am trying to show a new fragment where the nav_host_fragment is but I want the old one to show whenever I click on backButton or on an X in my app (I added that already). In the state that it is in right now it won't let me get out of the PlaylistFragment.

I also tried around with FragmentTransaction.add(...) but I couldn't figure how I get this working

My Code:

MainActivity.java:

 Fragment fragment = new PlayListFragment(position);

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        Fragment oldFragment = fragmentManager.findFragmentByTag(fragment.getClass().getName());

        //if oldFragment already exits in fragmentManager use it
        if (oldFragment != null) {
            //fragment = oldFragment;
        }

        fragmentTransaction.replace(R.id.nav_host_fragment, fragment, fragment.getClass().getName());

        fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);

        fragmentTransaction.addToBackStack("playlist");

        fragmentTransaction.commit();

PlaylistFragment.java:

        getActivity().getSupportFragmentManager().popBackStack("playlist", 0);

EDIT: When I tried putting null instead of "playlist" in the backstack: Yup. Then I see both fragments overflowing each other: Normal state: https://prnt.sc/12yitg5

When clicking on the "downloaded songs": https://prnt.sc/12yiu79

When clicking back in the fragment: https://prnt.sc/12yiuy6

EDIT: When I click on the X again it shows me the home fragment while bottom nav highlights the Library tab.

  • Tried to to put fragmentTransaction.addToBackStack(null); instead of fragmentTransaction.addToBackStack("playlist"); ? – Vatsal Dholakiya May 15 '21 at 10:51
  • Yup. Then I see both fragments overflowing each other: Normal state: https://prnt.sc/12yitg5 When clicking on the "downloaded songs": https://prnt.sc/12yiu79 When clicking back in the fragment: https://prnt.sc/12yiuy6 EDIT: When I click on the X again it shows me the home fragment while bottom nav highlights the Library tab. – Simon Mair May 15 '21 at 10:55
  • 1
    Visit this https://stackoverflow.com/a/67389269/12660050 only thing is you need to apply according to your code. – Vatsal Dholakiya May 15 '21 at 10:59
  • It worked. Thanks for finding this. Somehow I didn't. – Simon Mair May 15 '21 at 11:10
  • If you are using a `NavHostFragment`, you should *never* have to write a `FragmentTransaction` ever. You would [navigate to a new screen](https://developer.android.com/guide/navigation/navigation-getting-started#navigate). Why are you trying to use a `FragmentTransaction` at all? – ianhanniballake May 15 '21 at 13:30
  • Because I want to react to a onItemClick in a listview. How else could I show him new data, without a fragment? – Simon Mair May 16 '21 at 14:52

0 Answers0