Is it really necessary to always recreate fragments when navigating the bottom nav menu like in this code?
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.nav_home:
selectedFragment = new HomeFragment();
break;
case R.id.nav_favorites:
selectedFragment = new FavoritesFragment();
break;
case R.id.nav_search:
selectedFragment = new SearchFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment).commit();
return true;
}
};
I would rather like to create all my Fragments once in onCreate of the surrounding MainActivity and store them there as member variables. Then i could in the onNavigationItemSelected just use the references to my fragments instead of creating new fragments.
Is it okay to do it as described and not use the code above? Or could doing it as described cause complications somewhere?
Actually, creating them on create would be the best way. Also, sometimes people tend to add a lot of initializations on their on create and in the long run ur app might use too much memory when initializing the fragments every time you need them.