Search code examples
androidandroid-fragmentsbottomnavigationview

How to switch between fragments without recreating fragments each time?


While switching between fragments using bottomNavigationView the fragments are recreated every time when button is pressed.

Here is my code:

private boolean loadFragment(Fragment fragment) {
    //switching fragment
    if (fragment != null) {
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.fragmentguest, fragment)
                .commit();
        return true;
    }
    return false;
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
     Fragment fragment = null;

    switch (item.getItemId()) {
        case R.id.eventsguest:
            fragment = new Events();
            break;
        case R.id.about_usguest:
            fragment = new About_Us();
            break;
    }

    return loadFragment(fragment);
}

Solution

  • The replace method destroys your fragments. One workaround is to set them to Visibility.GONE, another (less easy) method is to hold them in a variable. If you do that, make sure you don't leak memory left and right.

    this question answered by meredrica in here