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?
– Mateus Carvalho
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.
– mutlei
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 yourActivity
, if you refer to these 10 Fragments as an app’s "screens", you may need to review this implementation.– Paulo Rodrigues