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

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

Posted by: admin March 11, 2020 Leave a comment


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);

… or the following, with show and hide?

    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

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.

How to&Answers:

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.


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


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