I am implementing the standard navigation drawer pattern for android, with about 10 fragments the user can navigate to from the drawer. Currently, I am creating a new Fragment every time a different navigation drawer item is clicked like so:
// When a new navigation item at index is clicked
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
Fragment newFragment = null;
if (index == 0)
fragment = new Fragment0();
...
ft.replace(R.id.container, newFragment);
ft.commit();
I have been wondering if it would be more efficient to do something like the following:
// Somewhere in onCreate
Fragment[] fragments = new Fragment[n];
fragments[0] = new Fragment0();
fragments[1] = new Fragment1();
...
// When a new navigation item (at index) is clicked
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.replace(R.id.container, fragments[index]);
ft.commit();
My main worry is that some of the fragments hold a significant amount of data (fairly large lists and lots of views). Would there be any issue holding all these fragments in memory and would it provide any advantage over instantiating new fragments every time (apart from faster switches between fragments)? Is there a generally accepted 'better' solution?