FragmentManager中Fragment的重复建立、复用问题

当咱们在Activity中使用 Fragment能够用FragmentManager去添加到对应个ViewGoup中使用spa

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

当咱们想复用的时候能够 code

// 经过tag找到对应的Fragment,在动态加载和静态加载中均可以使用
 secondFragment = (SecondFragment) fragmentManager.findFragmentByTag("fragment_second");

 在FragmentManager也能够执行replace方法替换对应ViewGroup中的Fragmentblog

replace(int containerViewId, Fragment fragment, String tag)

还可使用Remove方法删除对应ViewGroup的Fragmentrem

remove(Fragment fragment);

可是此处有个细节就是 当咱们使用Remove的时候不单单是把Fragment移出ViewGroup 同时也会执行Fragment的onDestry方法 也就是同时会销毁Fragmentget

相关文章
相关标签/搜索