片段是有趣的东西但是,我想,一旦你知道它们的怪癖,它们就是在多个设备上编写优秀代码的宝贵工具。
然而,在修复方向更改错误时,我遇到了墙。为了让我的片段能够工作,它需要访问一个属于它的View,它包含Activity,引导我进行一次快乐的追逐,试图找到Activity&片段生命周期相互作用。
我在我的“活动”视图中添加了一个片段onCreate()
方法:
// Only add a fragment once, as after it's been added it cannot be replaced (Even though there is a .replace() method. Which is a massive gaping hole in fragments as a technology if you ask me)
if(savedInstanceState == null) {
MainMenuFragment menu= new MainMenuFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.menuFrame, menu);
transaction.commit();
}
导致此活动 - >片段生命周期:
01-04 15:17:27.226: W/SinglePaneActivity 0: onCreate()
01-04 15:17:27.378: W/MainMenuFragment 0: onAttach() to SinglePaneActivity 0
01-04 15:17:27.378: W/MainMenuFragment 0: onCreate()
01-04 15:17:27.453: W/MainMenuFragment 0: onActivityCreated()
01-04 15:17:27.476: W/MainMenuFragment 0: onStart()
01-04 15:17:27.476: W/SinglePaneActivity 0: onStart()
01-04 15:17:27.476: W/SinglePaneActivity 0: onResume()
01-04 15:17:27.476: W/MainMenuFragment 0: onResume()
然而,方向更改突出显示通常不是这种情况,片段onCreate()
方法在其父活动onCreate()
之后未被调用。事实上,片段onAttach()
的第一个生命周期调用发生在甚至创建活动之前(null
作为参数传递):
01-04 15:10:49.589: W/MainMenuFragment 0: onPause()
01-04 15:10:49.589: W/SinglePaneActivity 0: onPause()
01-04 15:10:49.589: W/MainMenuFragment 0: onStop()
01-04 15:10:49.589: W/SinglePaneActivity 0: onStop()
01-04 15:10:49.589: W/MainMenuFragment 0: onDestroyView()
01-04 15:10:49.589: W/MainMenuFragment 0: onDestroy()
01-04 15:10:49.589: W/MainMenuFragment 0: onDetach()
01-04 15:10:49.609: W/SinglePaneActivity 0: onDestroy()
01-04 15:10:49.617: W/MainMenuFragment 1: onAttach() to null
01-04 15:10:49.617: W/MainMenuFragment 1: onCreate()
01-04 15:10:49.617: W/SinglePaneActivity 1: onCreate()
01-04 15:10:49.890: W/MainMenuFragment 1: onActivityCreated()
01-04 15:10:49.917: W/MainMenuFragment 1: onStart()
01-04 15:10:49.917: W/SinglePaneActivity 1: onStart()
01-04 15:10:49.921: W/SinglePaneActivity 1: onResume()
01-04 15:10:49.921: W/MainMenuFragment 1: onResume()
我完全不知道为什么会这样。任何人都可以解释为什么Fragment.onAttach()
在创建包含活动之前被调用了吗?
我得到的片段不需要访问其包含的活动(直到UI交互)按预期工作。
答案 0 :(得分:10)
Argh,
01-04 15:46:23.175: W/MainMenuFragment 0: onAttach() to SinglePaneActivity 0
01-04 15:46:23.179: W/MainMenuFragment 0: onCreate()
01-04 15:46:23.246: W/MainMenuFragment 0: onActivityCreated() with Activity SinglePaneActivity 0
01-04 15:46:23.269: W/MainMenuFragment 0: onStart()
01-04 15:46:23.269: W/SinglePaneActivity 0: onStart()
为什么有一个onAttach()
方法,我不知道。特别是因为“附加”发生在有活动之前。
我需要的方法当然是onActivityCreated()
,它发生在Fragment lifecycle events的“创建”集中的最终调用。