2011年6月9日 星期四

Fragment在螢幕旋轉時產生的問題

說實在Andrid 3.0真的是個半完成品,我找了好幾篇討論fragment怎麼處理螢幕旋轉,都只看到一堆只能歸類為workaround的東西。
在xml裡面寫然後直接setContentView只會吃Error,和你說fragment已經被創造了這樣。所以如果你的port/land的layout是分開的,需要override onConfigureChanged來重新setContentView的話,xml裡根本不能用。你需要用以後,自行利用FragmentTransaction把Fragment加進去。

當你旋轉螢幕,呼叫setContentView時Fragment的生命週期不會有任何變動(on系列的method全部不會被call),但是由於FrameLayout的instance變了,你在螢幕上是看不到Fragment的
此時如果你想重新add Fragment,就會吃到Fragment already added的錯誤。所以你需要先把他remove掉後重新add,此時他的生命週期會跑:
  • onPause
  • onStop
  • onDestroyView
  • onCreateView
  • onActivityCreated
  • onStart
  • onResume
你可以看到他跑了onDestroyView,所以你本來在裡面的東西就通通消失重新再來。但是Fragment instance本身是沒有變動的,所以你可以先在onStop把你要的東西救出來保存在field裡面,然後在onStart重新加回去或做其他處理。

沒有留言:

CODE { display: block; /* fixes a strange ie margin bug */ font-family: Courier New; font-size: 8pt; overflow:auto; background: #f0f0f0 url(http://klcintw.images.googlepages.com/Code_BG.gif) left top repeat-y; border: 1px solid #ccc; padding: 10px 10px 10px 21px; max-height:200px; height:200px; // for IE6 line-height: 1.2em; } #quote { display: block; /* fixes a strange ie margin bug */ font-family: Verdana; font-size: 10pt; overflow:auto; background: #f7f7f7 url(http://lh5.ggpht.com/_z-VThISftkI/SXUlpyfw9ZI/AAAAAAAABYY/e3GUx9_Z4TE/s288/quote-l.gif) left top no-repeat; border: 4px dotted #ccc; padding: 15px 15px 15px 31px; /*up right bottom left*/ max-height:300px; line-height: 1.2em; }