Android snippets: when to use hide / show or add / remove / replace?

Suppose I want to replace the current fragment as a container with another. Better use a replacement ...

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

One way to make this more efficient? It is not possible to find much information about when to use these methods or how they affect the life cycle of fragments. Thank!

+86
android android-fragments
Oct 31
source share
2 answers

You should consider what you plan to do with the fragment in order to decide which path to follow. If you use a FragmentTransaction to hide a fragment, it can still be in the working state of its life cycle, but its user interface has been disconnected from the window so that it no longer displays. That way, you can technically still interact with the fragment and reconnect its interface, which you will need. If you replace the fragment, you actually pull it out of the container and it will go through all the break events in the life cycle (onPause, onStop, etc.), and if for some reason you need this fragment again, you will have to insert it back to the container and let it run all its initialization again.

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

+103
Nov 01 '12 at 20:32
source share

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

+4
Oct 31
source share



All Articles