第一种方式replace,每次都会重新走生命周期
private ConcurrentHashMap<String, BaseFragment> fragments = new ConcurrentHashMap<>();
private FragmentManager fm;
private FragmentTransaction tx;
private String homePagerFragment = HomePagerFragment.class.getSimpleName();
private BaseFragment mCurrentFragment;
private void switchPages(String selectPageIndex) {
BaseFragment baseFragment = fragments.get(selectPageIndex);
if (baseFragment == null) {
if (selectPageIndex.equals(homePagerFragment)) {
baseFragment = new HomePagerFragment();
fragments.put(homePagerFragment, baseFragment);
} else if (selectPageIndex.equals(filePagerFragment)) {
baseFragment = new FilePagerFragment();
fragments.put(filePagerFragment, baseFragment);
}
}
mCurrentFragment = baseFragment;
fm = getSupportFragmentManager();
tx = fm.beginTransaction();
tx.replace(R.id.vp_content_fragment_pages, baseFragment);
tx.addToBackStack(selectPageIndex);
tx.commitAllowingStateLoss();
}
第二次方式add,首次会走生命周期,第二次不再重新走生命周期
private FragmentManager fm;
private FragmentTransaction transaction;
private Fragment mCurrentFragment;
public static String generalView = GeneralInformationFragment.class.getSimpleName();
private void switchPages(String selectPageIndex) {
fm = getSupportFragmentManager();
transaction = fm.beginTransaction();
if (mCurrentFragment != null) {
transaction.hide(mCurrentFragment);
}
Fragment fragmentByTag = fm.findFragmentByTag(selectPageIndex);
if (fragmentByTag == null) {
if (selectPageIndex.equals(generalView)) {
fragmentByTag = new GeneralInformationFragment();
} else if (selectPageIndex.equals(networkView)) {
fragmentByTag = new NetworkFragment();
} else if (selectPageIndex.equals(storageView)) {
fragmentByTag = new StorageFragment();
}
transaction.add(R.id.fl_system_status_content, fragmentByTag, selectPageIndex);
}
mCurrentFragment = fragmentByTag;
transaction.show(fragmentByTag);
transaction.commit();
}
博客介绍了两种方式的生命周期情况。replace方式每次都会重新走生命周期,而add方式首次会走生命周期,第二次则不再重新走。
1388

被折叠的 条评论
为什么被折叠?



