第一種方式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 = getFragmentManager(); 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(); }