片段是有趣的事情,但我認爲,一旦你知道他們的怪癖,他們是在多個設備上編寫好代碼的寶貴工具。片段/活動生命週期和方向變化
但是,在修復方向更改錯誤時,我碰到了牆壁。對於我的片段來說,它需要訪問一個屬於它的視圖,該視圖包含一個活動,引導我進行快速追逐,試圖找出活動的片段生命週期如何交互。
我加入到我的活動片段查看它的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()
的方向變化但強調了這ISN通常情況下,片段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()
在包含Activity之前被調用?
碎片我得到了哪些不需要訪問其包含的活動(直到UI交互)按預期工作。
請幫助我http://stackoverflow.com/questions/12331787/save-fragment-objects – user4o01 2012-09-08 14:55:58