Return to Fragment without creating it again

Asked

Viewed 722 times

-1

I have a fragment that shows a Map, and in the app has a registration screen, the first fragment to be created is the Map, if the user wants to register will start another Fragment, after he register I want to return to the Map Fragment without needing to instance it again.

2 answers

1

If you’re working with Fragments, so you have a manager for them, so you actually only need to instantiate once these Fragments and replace in container as your need.

In the creation of its Activity, you can have these two next blocks, with the manager:

FragmentManager fragmentManager = getFragmentManager()
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

And both Fragments:

CadastroFragment cadastro = new CadastroFragment();
MapaFragment mapa = new MapaFragment();

Then just make the transaction when necessary. For registration, for example:

fragmentTransaction.replace(R.id.fragment_container, cadastro);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
  • Right, but for example I just wanted Cadastrofragment() when the guy actually clicked to go to the registration screen... If I have 10 fragments per ex, I would have to create them all earlier on Activity?

  • 1

    I believe so. Although in cell phones the Garbage Collector should be more active than in Java itself, so maybe you can keep creating Fragments whenever needed, as Dalvik must clear the memory more often than the JVM.

  • Yes, because I don’t believe there’s any other way for you to keep the object without having it. Now, to be clear, Fragment is a portion of the interface in your Activity, if you refer to these 10 Fragments as an app’s "screens", you may need to review this implementation.

0

To solve this problem you can solve by creating Fragment and adding it and not putting in any container by doing:

public static final String FRAG_A_TAG="fragmentA";
FragmentManager mFragManager = getSupportFragmentManager();
FragmentTransaction mTransaction = mFragManager.beginTransaction();
//criar um fragment 
FragmentA fragA= new FragmentA();
//adicionar o fragment pelo tag
mTransaction.add(fragA,FRAG_A_TAG).commit();

This way the Fragment was added but was not placed in any container, at the time of re-using the Fragment just do:

FragA = mFragManager.findFragmentByTag(FRAG_A_TAG);

And from here Voce can put Fragment in the container as it normally does.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.