0

I have a Activity where I load 3 fragments one after another

  • FragmentA
  • FragmentB
  • FragmentC

Flow is Like this I have used Adding fragment one above another

Start-Activity -----> Load FragmentA ----> Load FragmentB ----> Load FragmentC


What I am trying to do now is:

Now assuming now FragmentC is the top fragment shown

I want to find the FragmentA from the stack and just show it instead of creating a fragmentA all over again


Code I have used to add fragmentA is for Example:

            Fragment fragment = null;
            FragmentTransaction fragmentTransaction = null;
            fragment = new FragmentA();
            fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.addToBackStack(FragmentA.class.getSimpleName());
            fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
            fragmentTransaction.add(R.id.container, fragment, FragmentA.class.getSimpleName());

            if(fragment!=null && fragmentTransaction!=null){
                fragmentTransaction.commitAllowingStateLoss();
            }
Devrath
  • 39,949
  • 51
  • 178
  • 266
  • instead of creating new fragment, find the fragment by tag or id. for more have look [this](https://stackoverflow.com/a/32139709/5110595) – Hemant Parmar Jan 30 '18 at 05:56

4 Answers4

0

Look at FragmentManager.getBackStackEntryAt method, from there you can go back to any fragment of your history…

JBA
  • 2,859
  • 1
  • 20
  • 35
0

Loop through the back stack entries, meanwhile, if you find any matching Fragment by id or tag, just pop back stack inclusive with fragment A's name/tag so that the fragment A is just displayed rather than adding once again.

Debdeep
  • 662
  • 10
  • 21
0

You are giving a tag, fragmentTransaction.addToBackStack(FragmentA.class.getSimpleName()); to the transaction , you can use the same tag to find the fragment in the backstack, before creating a new frgament, check the backstack for the fragment using findFragmentByTag on the fragment manager, if it exist, the method returns the fragment otherwise null

sharp
  • 1,199
  • 14
  • 38
Sony
  • 6,934
  • 4
  • 41
  • 63
0

The example code to retrieve a fragment by Tag would look like this

FragmentA frA = getSupportFragmentManager().findFragmentByTag(FragmentA.class.getSimpleName()); 

and if it's not null you can reuse it in your container

if(frA != null) {
   FragmentTransaction fragmentTransaction = getSupportFragmentManager.beginTransaction();
   fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
   //you could add this transactionn to backstack again here if you want to be able to pop it later
   fragmentTransaction.add(R.id.container, frA, FragmentA.class.getSimpleName());
} else {
   //if your fragment is null as it was destroyed previously you can create a new one here
}
Rainmaker
  • 8,993
  • 5
  • 45
  • 72