简体   繁体   English

创建一个片段并重用它

[英]Create one fragment and reuse it

I have 2 fragments a and b in which there is a container for fragments, I need to place a separate fragment x in these 2 containers so that the nested fragment x is not recreated when switching between fragments a and b, create a singleton from fragment x.我有2个片段a和b,其中有一个片段容器,我需要在这2个容器中放置一个单独的片段x,以便在片段a和b之间切换时不会重新创建嵌套片段x,从片段创建一个单例X。 Please tell me how can i implement this请告诉我如何实现这个

if i was in this situation, i would modify my design such that x falls outside of a and b.如果我处于这种情况,我会修改我的设计,使 x 落在 a 和 b 之外。 this is because it would be more efficient.这是因为它会更有效率。 because every time you switch the fragments, lets say from a to b, a enters paused state and b enters resumed state.因为每次切换片段时,比如说从 a 到 b,a 进入paused状态,b 进入resumed状态。 change of state would need component to act on their widgets which would consume processing power.状态的改变需要组件作用于它们的小部件,这会消耗处理能力。 if x was outside, then no processing is required because it's not re-rendered.如果 x 在外面,则不需要处理,因为它不会重新渲染。 if you still want to implement things this way, then make the data persistent, not the entire fragment .如果您仍想以这种方式实现事物,则使data持久化,而不是整个fragment when a fragment is rendered on screen, it's children must also be rendered.当一个片段在屏幕上渲染时,它的孩子也必须被渲染。 there is no other option.没有其他选择。 you cannot just render a block on screen but expect some of its children to already be rendered on screen before parent has rendered.您不能只在屏幕上渲染一个块,而是希望它的一些子级在父级渲染之前已经在屏幕上渲染。 this is why you'll see onCreate passes a Bundle param.这就是为什么你会看到onCreate传递了一个Bundle参数。 the param contains all data that required retention and that's why things are able to be rendered the same.参数包含所有需要保留的数据,这就是为什么事情可以呈现相同的原因。 it's a good idea to separate data from architecture .数据架构分开是个好主意。 hope this helps.希望这可以帮助。

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

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