Android Fragments:何时使用隐藏/显示或添加/删除/替换? [英] Android Fragments: When to use hide/show or add/remove/replace?

查看:25
本文介绍了Android Fragments:何时使用隐藏/显示或添加/删除/替换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我希望将某个容器视图中的当前片段替换为另一个.是不是用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!

推荐答案

您应该考虑您计划对片段做什么来决定要遵循的路径.如果使用 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.

这篇关于Android Fragments:何时使用隐藏/显示或添加/删除/替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆