Fragment.replace會銷毀實例


項目中如下:

<FrameLayout
	android:id="@+id/bottombar"
	android:layout_width="match_parent"
	android:layout_height="wrap_content">
<LinearLayout android:id="@+id/bar1"></LinearLayout>
     <LinearLayout android:id="@+id/bar2" android:visibility="gone"></LinearLayout> </FrameLayout>

在同一個位置需要顯示和隱藏視圖相近的兩個下bar,由於bar1和bar2內容都非常多,因此會導致這個xml文件非常擁擠。為了使代碼簡潔,嘗試使用兩個Fragment在此處進行替換處理,而且好處之一是Fragment在替換的時候有現成的setCustomAnimations()函數實現動畫效果。

private void switchBottomFragment(Fragment in, Fragment out){
	FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
	fragmentTransaction.setCustomAnimations(R.animator.bottom_category_anim_up, R.animator.bottom_category_anim_down);
	fragmentTransaction.replace(R.id.bottom_category, in);
	fragmentTransaction.commit();
	out = null;	
}

 Fragment in:要顯示的bar

   Fragment out:要隱藏的bar

從表面上來看,效果實現的很好,沒有什么問題,但出現了一個問題bar1中有一個RadioGroup,bar1退出的時候我希望clearCheck不選中之前的選中項。因為知道replace會銷毀View以及Fragment實例,所以直接在onCreateView中使用了ViewGroup.clearCheck(),然而clearCheck並沒有發揮作用。仔細想想,原因如下,而且這里很容易產生難以發現的問題。

replace()調用的時候,該位置被替換的Fragment實例和視圖都會被銷毀,但是並不會立即被回收,所以如果在Activity中設置了該Fragment的變量,則該變量對應的實例對象還是舊的,但是整個顯示的視圖對象卻已經是新的了。因此會被替換的Fragment對象一定不能作為變量存在,如果需要用到對象實例,可以使用findFragmentByTag獲取實時對象,並且如果需要保存原先的實例,則還需要在onSaveInstanceState中保存需要保存的狀態值。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM