0

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?

javaguy
  • 149
  • 1
  • 6
  • you can do that using singleton pattern . Check this answer : https://stackoverflow.com/questions/14839152/fragment-as-a-singleton-in-android. – Jawad Ahmed Aug 11 '19 at 12:28
  • Using a singleton pattern you will only create one instance of each fragment and will reuse them again and again. – Jawad Ahmed Aug 11 '19 at 12:29

2 Answers2

0

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.

Jian Astrero
  • 744
  • 6
  • 19
  • I'll go with this answer because there are not that many fragments in my app and i hope that therefore the performance penalty mentioned in the other answer can be disregarded. – javaguy Aug 13 '19 at 16:35
0

You would have to be responsible for saving your fragments state, so on recreation, your data would be readily available. You could try something like this

https://proandroiddev.com/fragments-swapping-with-bottom-bar-ffbd265bd742

Although there are many approaches you could attempt.

You could create all the fragments at once and swap them with your bottom navigation. But I wouldn't recommend that for obvious navigation and performance reasons.

Richard Dapice
  • 838
  • 5
  • 10