与其活动有关的片段生命周期
情况 我的活动等待异步操作,在收到异步操作的回复后,它需要将信息传递给其中的 2 个片段。
要求 1. 两个片段都需要调用 onCreateView
来加载布局, 2. 他们需要将自己附加到他们的 Activity 上,以便 getActivity()
工作。
我在这两个片段中编写了一个 setData() 方法,并在活动生命周期中寻找“正确”的位置来调用它们。
活动的 onCreate()
不起作用,活动的 onStart()
不起作用,片段的 onStart()
不起作用。
什么都不起作用,我在这里缺少什么?
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.
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.
I wrote a setData()
method in both the fragments and am looking for the "correct" place in the activity's lifecycle to invoke them.
onCreate()
of the activity does not work, onStart()
of the activity does not work and onStart()
of the fragment does not work.
Nothing works, what am I missing here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Fragment 生命周期 的官方文档清楚地解释了这一点 - 请参考如果有不清楚的地方,然后提出后续问题。
The official documentation for the Fragment lifecycle explains this clearly - please refer to it and then ask follow-up questions if something is unclear.
此图将有助于理解这两个生命周期。
正如许多人抱怨的那样,这个生命周期太复杂了,这在某种程度上是有道理的,在 Google I/O 2018 上,他们建议使用架构组件框架。请查看此文档
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. Please check this Docs
当您位于
Activity2---->backpress--->Fragment2(Activity1)
时---意味着Activity1
再次从fragment2 等
OnAactivityCreated()
方法Activity1
已完全加载....因此我们可以调用 Activity1 的setData()
方法。 ..when you are at
Activity2---->backpress--->Fragment2(Activity1)
---meansActivity1
again attach fromfragment2
so onOnAactivityCreated()
methodActivity1
is completely loaded ....so at that we can callsetData()
method of your Activity1...onAttachFragment()-activity 在 onCreate()-activity 之前和 onAttach()-fragment 之后调用
onAttachFragment()-activity is called before onCreate()-activity and after onAttach()-fragment
在片段的 onStop 上调用 onDestroy。这应该在片段启动时调用 onCreate。
让我知道是否可以作为解决您问题的理想解决方案。
Call onDestroy on onStop of your fragment. This should call onCreate when the fragment is launched.
Let me know if works as an ideal solution for your problem.