1

I have 4 fragments, and what i'm trying to do, is, freeze the fragment A when i replace it with the new fragment B / C or D. Then replace B / C / D with Fragment A, the fragment won't change the state.

I have Google Maps, and i'm trying to return to the saved state, but the problem is that the fragment is re-created ...

I can do it when i lock the screen, and when it goes to the new intent.

If someone could help me, really apreciate.

Thanks for helping :D

Tek
  • 25
  • 7

2 Answers2

1

Try this

Open fragments using this function.You have to pass the tag for that perticular fragment.

private Fragment currentFragment;

    public void openNewFragment(Fragment f, String tag) {

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        Fragment fragment = getSupportFragmentManager().findFragmentByTag(tag);

        {
            if (fragment != null) {
                if (currentFragment != null) {
                    if (fragment.getClass().equals(currentFragment.getClass())) {
                        return;
                    }
                }

                ft.show(fragment);
                ft.hide(currentFragment);
                currentFragment = fragment;

            } else {
                if (currentFragment != null)
                    ft.hide(currentFragment);
                ft.add(R.id.container, f, tag);
                currentFragment = f;
            }
            ft.commit();
        }

    }
AbhayBohra
  • 2,047
  • 24
  • 36
0

Show and hide the fragments with the following code:

val ft: FragmentTransaction = fragmentManager.beginTransaction()

if (firstFragment!= null) ft.hide(firstFragment)
if (secondFragment!= null) ft.show(secondFragment)
else {
    secondFragment = SecondFragment.newInstance()
    ft.add(container, secondFragment )
}
if (thirdFragment!= null) ft.hide(thirdFragment)
if (fourthFragment!= null) ft.hide(fourthFragment)

ft.commitNow()

This way you will keep your fragments as you left them. Having them all as null at first helps with the memory usage.

Viktor Stojanov
  • 708
  • 6
  • 20
  • secondFragment = SecondFragment.newInstance() ? – Tek Jul 30 '18 at 10:54
  • You can call `secondFragment = SecondFragment()` too. Here a bit a more about the [new instance](https://stackoverflow.com/questions/9245408/best-practice-for-instantiating-a-new-android-fragment) – Viktor Stojanov Jul 30 '18 at 10:58
  • You are a genius! :OOOOOOO IT WORKED Like 2 days arround this problem ... THANKS!!! – Tek Jul 30 '18 at 11:08