Android Fragments: When to use hide/show or add/remove/replace?

Suppose I wish to replace the current fragment in some container view with another. Is it better to use replace...

    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.replace(R.id.fragment_container, newFragment, null);
    ft.commit();

... or the following, with show and hide?

    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.hide(oldFragment);
    ft.show(newFragment);
    ft.commit();

Is one way of doing this more efficient? Can't find much information on when to use these methods, or how they affect the lifecycle of the fragments involved. Thanks!


Solution 1:

You should consider what you plan to do with the fragment to decide which path to follow. If you use a FragmentTransaction to hide the fragment, then it can still be in the running state of its lifecycle, but its UI has been detached from the window so it's no longer visible. So you could technically still interact with the fragment and reattach its UI later you need to. If you replace the fragment, the you are actually pulling it out of the container and it will go through all of the teardown events in the lifecycle (onPause, onStop, etc) and if for some reason you need that fragment again you would have to insert it back into the container and let it run through all of its initialization again.

If there is a high probability that you will need that fragment again, then just hide it because it's a less expensive operation to redraw it's layout than to completely reinitialize it.

Solution 2:

You basically answered yourself. If you want to replace (so old fragment is no longer needed) use replace() if you want to temporary hide it then do hide().