fragment add或replace兩種方式添加多個fragment

第一種方式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();
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章