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

AndroidAndroid Fragments

Android Problem Overview


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!

Android Solutions


Solution 1 - Android

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 - Android

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().

Solution 3 - Android

I used hide/Show method in my activity with 4 fragments its solved my solution but some time randomly when i show my dialog it give window bad token exception when i used add and replace method then bad token exception is not occur so i think show/hide method is not perfect

Solution 4 - Android

If the view is "heavy" I think the hide/show should be used. There is such callback: onHiddenChanged. If you use hide/show it would be helpful.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRobert KarlView Question on Stackoverflow
Solution 1 - AndroidDavid C. Sainte-ClaireView Answer on Stackoverflow
Solution 2 - AndroidMarcin OrlowskiView Answer on Stackoverflow
Solution 3 - AndroidDishant KawatraView Answer on Stackoverflow
Solution 4 - AndroidVahanView Answer on Stackoverflow