當我們在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