简体   繁体   English

片段生命周期与它的活动有关

[英]Fragment lifecycle with respect to it's activity

Situation My activity waits on an Async operation and after it hears back from async operation, it needs to pass information to 2 fragments inside it. 情况我的活动等待异步操作,在它从异步操作中听到后,它需要将信息传递给其中的2个片段。

Requirement 1. Both fragments need their onCreateView calls to be done for them to have their layouts loaded, 2. They need for themselves to be attached to their activity so that getActivity() works. 要求 1.两个片段都需要对它们进行onCreateView调用才能加载它们的布局.2。它们需要自己附加到它们的活动,以便getActivity()工作。

I wrote a setData() method in both the fragments and am looking for the "correct" place in the activity's lifecycle to invoke them. 我在两个片段中都写了一个setData()方法,并在活动的生命周期中寻找“正确”的位置来调用它们。

onCreate() of the activity does not work, onStart() of the activity does not work and onStart() of the fragment does not work. onCreate()的活动无法正常工作, onStart()活动的不工作, onStart()的片段不起作用。

Nothing works, what am I missing here? 什么都行不通,我在这里缺少什么?

片段生命周期的官方文档清楚地解释了这一点 - 请参考它,然后在不清楚的情况下询问后续问题。

This Image will be helpful to understand both life cycles together. 此图像将有助于同时了解两个生命周期。

As many people complaints and it is somewhat valid argument that this life cycle is too complicated, in Google I/O 2018,They have suggested to use Architecture component Framework. 由于许多人抱怨并且这个生命周期过于复杂是一个有效的论据,在Google I / O 2018中,他们建议使用架构组件框架。 Please check this Docs 请查看此文档

在此输入图像描述

当你在Activity2---->backpress--->Fragment2(Activity1) ---意味着Activity1再次从fragment2附加,所以OnAactivityCreated()方法Activity1被完全加载....所以我们可以调用setData() Activity1的方法......

onAttachFragment() - 在onCreate() - activity之前和onAttach()之后调用activity - 片段

Call onDestroy on onStop of your fragment. 在片段的onStop上调用onDestroy。 This should call onCreate when the fragment is launched. 这应该在片段启动时调用onCreate。 Let me know if works as an ideal solution for your problem. 让我知道是否可以作为您问题的理想解决方案。

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

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