简体   繁体   English

了解片段和活动生命周期以及向后导航

[英]Understanding the fragment and activity lifecycle and backwards navigation

I'm trying to understand some odd behavior. 我试图了解一些奇怪的行为。 I have an ActivityA that calls a method in onCreate() to add FragmentA to R.id.fragment_container. 我有一个ActivityA,它调用onCreate()中的方法将FragmentA添加到R.id.fragment_container。 Inside FragmentA I have a button that attaches FragmentB by using ActivityA's fragment manager (getActivity().getSupportFragmentManager()) and replacing the R.id.fragment_container and I also add it to the backstack. 在FragmentA内部,我有一个按钮,它通过使用ActivityA的片段管理器(getActivity()。getSupportFragmentManager())并替换R.id.fragment_container来附加FragmentB,并且还将其添加到后堆栈中。 I also have another button that starts a new ActivityB. 我还有另一个按钮可以启动新的ActivityB。 When I navigate back from ActivityB I get: ActivityA onResume(), FragmentA onResume(). 当我从ActivityB导航回来时,我得到:ActivityA onResume(),FragmentA onResume()。 But when I navigate back from FragmentB I get: FragmentB onCreateView(), FragmentB onActivityCreated() then the 2 onResume(). 但是,当我从FragmentB导航回来时,我得到:FragmentB onCreateView(),FragmentB onActivityCreated()然后是2 onResume()。

So my questions is...why is the view state saved when a new activity is launched and not when the fragment is replaced and reattached. 所以我的问题是...为什么在启动新活动时保存视图状态,而不是在替换并重新连接片段时保存视图状态? It looks much better to just restore that state rather than recreate the views and fetch that data again. 只恢复该状态而不是重新创建视图并再次获取该数据看起来要好得多。 This seems like opposite behavior from what I would expect so I'm clearly missing some fragment state saving/restoration step or something. 这似乎与我预期的行为相反,因此我显然缺少某些碎片状态保存/恢复步骤或其他内容。 It seems like the activity is just pausing FragmentA (and ActivityA) when ActivityB is launched and restoring it on back pressed but when FragmentB is attached FragmentA gets completely destroyed. 似乎在启动ActivityB时,该活动只是暂停FragmentA(和ActivityA),并在按下时恢复它,但是在连接FragmentB时,FragmentA被完全破坏了。 I'm sure there's a way to prevent this I just can't seem to figure it out. 我敢肯定,有一种方法可以防止这种情况,但我似乎无法弄清楚。 Thoughts? 有什么想法吗?

Just below your question are four tags android,android-fragments,android-lifecycle& android-navigation .Put your cursor over it for a while a black box will pop up . 在您的问题下方是四个标签android,android-fragments,android-lifecycle&android-navigation。将光标放在其上一会儿就会弹出一个黑匣子 click on info tab and you will get best links to study that topics along with links to books . 单击“信息”选项卡,您将获得研究该主题的最佳链接以及书籍链接。

Hope this will help you 希望这个能对您有所帮助

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

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