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!

62307 次浏览

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

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.

如果您很有可能再次需要该片段,那么只需隐藏它,因为重新绘制它的布局比完全重新初始化它的操作成本更低。

我在我的活动中使用了4个片段的 hide/Show 方法它解决了我的问题,但是有时候当我显示我的对话框的时候它会给窗口坏的令牌异常当我使用 add 和 place 方法的时候坏的令牌异常不会发生所以我认为 Show/hide 方法并不完美

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.