FragmentManager中Fragment的重復創建、復用問題


當我們在Activity中使用 Fragment可以用FragmentManager去添加到對應個ViewGoup中使用

FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction transaction = fragmentManager.beginTransaction(); transaction.add(R.id.fragment_container,fragment,tag); transaction.commit();

當我們想復用的時候可以 

// 通過tag找到對應的Fragment,在動態加載和靜態加載中都可以使用
 secondFragment = (SecondFragment) fragmentManager.findFragmentByTag("fragment_second");

 在FragmentManager也可以執行replace方法替換對應ViewGroup中的Fragment

replace(int containerViewId, Fragment fragment, String tag)

還可以使用Remove方法刪除對應ViewGroup的Fragment

remove(Fragment fragment);

但是此處有個細節就是 當我們使用Remove的時候不僅僅是把Fragment移出ViewGroup 同時也會執行Fragment的onDestry方法 也就是同時會銷毀Fragment

 


免責聲明!

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



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