3

When I replace a fragment, it gets destroyed. I tried to create the fragment in activity's onCreate and hold its reference in the activity and use it when I "re show" or "reopen" it by calling replace with the reference, but that did not help and the fragment got destroyed (when replaced by another fragment) and recreated. What should be the solution?

What I'm trying to achieve is something like say WhatsApp where fragments should not be destroyed when not visible, except I'm not using a sliding gesture but rather regular buttons.

Thanks.

Ümañg ßürmån
  • 9,695
  • 4
  • 24
  • 41
Kh5
  • 167
  • 2
  • 10

4 Answers4

6

You need to use addToBackStack() to remeber the fragment transaction like below:-

FragmentA fragmentA = new FragmentA();
getFragmentManager().beginTransaction()
    .replace(R.id.YOUR_CONTENT,fragmentA,"YOUR_TARGET_FRAGMENT_TAG")
    .addToBackStack("YOUR_SOURCE_FRAGMENT_TAG").commit();

And u can check the fragment is it already present in the stack or not like below

Fragment fragment = getFragmentManager().findFragmentByTag("YOUR_TARGET_FRAGMENT_TAG");

 if (fragment!=null && fragment instanceof FragmentA) {
   //you are good to go, do your logic   
    }
Ravindra Kushwaha
  • 7,846
  • 14
  • 53
  • 103
0

Use a bundle to save state information and restore it perhaps within onCreate()?

Ravindra Kushwaha
  • 7,846
  • 14
  • 53
  • 103
James
  • 47
  • 7
0

FragmentTransaction.replace(): Replace an existing fragment that was added to a container.

So this removes the Fragment from the stack.

Use FragmentTransaction.addToBackStack() to add the Fragment on top of another(s) (the stack).

shkschneider
  • 17,833
  • 13
  • 59
  • 112
0

The solution is ViewPager with PagerAdapter, more specifically to my case is FragmentPagerAdapter.

Implementation of PagerAdapter that represents each page as a Fragment that is persistently kept in the fragment manager as long as the user can return to the page. This version of the pager is best for use when there are a handful of typically more static fragments to be paged through, such as a set of tabs. The fragment of each page the user visits will be kept in memory, though its view hierarchy may be destroyed when not visible.

https://developer.android.com/reference/android/support/v4/app/FragmentPagerAdapter

I have dealt with it before very very long ago, though I didn't consider it because back then I used it with TabLayout and I thought they were tightly coupled.

Kh5
  • 167
  • 2
  • 10