Android的碎片:何时使用隐藏/显示或添加/删除/更换?碎片、Android

2023-09-12 22:44:30 作者:纠结体

假设我希望取代目前的片段与其他一些容器视图。是更好地使用替代...

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();
    hide(oldFragment);
    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!

推荐答案

您应该考虑你打算做什么用的片段来决定采用哪一种路径。如果使用FragmentTransaction隐藏片段,那么它仍然可以在其生命周期的运行状态,但它的UI已经脱离了窗口,以便它不再可见。所以,你可以在技术上仍与片段互动,稍后再连接它的UI,你需要。如果更换的片段时,你实际上是拉出来的容器,它会遍历所有的拆机事件的生命周期(的onPause,的onStop等),如果由于某种原因,你需要的片段再次你将不得不将它放回容器中,并让其通过其所有的初始化再次运行。 如果有,你将再次需要一个片段的概率很高,那么就隐藏它,因为它是一个不太昂贵的操作,重新绘制它的布局,而不是完全重新初始化。

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.