简体   繁体   English

为什么总是newInstance或片段的对象

[英]Why are always newInstance or object of fragments

I need to know why do we always instantiate a new object of fragment using either A.newInstance() or A() if we know there is already an instance exists. 我需要知道为什么我们总是使用A.newInstance()或A()来实例化一个新的片段对象,如果我们知道已经有一个实例存在的话。 Does it not increase memory uses by the app in Android? 它不会增加Android中的应用程序的内存使用量吗?

In my case I have an activity and multiple fragments which are opened by menus present in drawer fragment. 在我的情况下,我有一个活动和多个片段,由抽屉片段中的菜单打开。 These fragments further might open other fragments which are not listed in drawer menu. 这些片段还可能会打开抽屉菜单中未列出的其他片段。 So I am wondering if is it normal to create new instances of secondary fragments by top fragment each time. 所以我想知道每次按顶部片段创建二级片段的新实例是否正常。 The same is true for top level fragments. 顶级片段也是如此。 My flow is explained below: 我的流程解释如下:

  1. Fragment A (new instance first time) 片段A(新实例第一次)
  2. Fragment B (lower level fragment/new instance, instantiated by A) 片段B(较低级别片段/新实例,由A实例化)
  3. Back to A (by pressing up arrow) 回到A(按向上箭头)
  4. Fragment B (lower level fragment/again new instance, instantiated by A) 片段B(较低级别片段/再次新实例,由A实例化)
  5. Back to A (by pressing up arrow) 回到A(按向上箭头)
  6. Fragment X (new instance first time/top level fragment/from drawer menu) 片段X(新实例第一次/顶级片段/来自抽屉菜单)
  7. Fragment A (again new instance of A/top level fragment/from drawer menu) 片段A(再次是A /顶级片段的新实例/来自抽屉菜单)

Is it correct to have multiple instances of fragments A (top level / point 7) and B (lower level / point 4)? 具有多个片段A(顶级/第7点)和B(较低级别/第4点)的实例是否正确? As I am using this strategy? 当我使用这个策略?

You shouldn't instantiate new fragments everytime you "toggle between pages" 每次“在页面之间切换”时,不应该实例化新的片段

You should add them into the FragmentManager when needed with a tag (an optional string parameter), then find them using that tag ( findFragmentByTag ) , and replace the current shown Fragment if you could find the other. 您应该在需要时使用标记(可选的字符串参数) add它们add到FragmentManager中,然后使用该标记( findFragmentByTag )找到它们,如果找到另一个,则replace当前显示的Fragment。 Otherwise, you can instantiate a new one. 否则,您可以实例化一个新的。

You'll also need to place Fragments on the back stack ( addToBackStack ) , I think, so they are held onto by the FragmentManager 你还需要在后面的堆栈上放置Fragments( addToBackStack ),所以它们被FragmentManager addToBackStack

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM