Fragment中add与replace的区别、Fragment重叠问题

add与replace:

replace每次都会重新初始化fragment,它是先remove掉相同id的fragment,再add当前fragment。

add不会回每次都初始化fragment,一般配合hide()和show()方法

 

Fragment重叠问题:

使用add,如果应用放在后台,或以其他方式被系统销毁,再打开时,hide()中引用的fragment会销毁,可能会出现布局重叠bug,所以在使用replace或使用add时,添加一个tag参数,通过tag的id去寻找fragment;

private HomeFragment mHomeFragment;
public void showHomeFragment(Bundle bundle, String tag) {
    FragmentManager fragmentManager = getSupportFragmentManager();
    if (bundle != null) {
        mHomeFragment = (HomeFragment) fragmentManager.findFragmentByTag(tag);
    }
    if (mHomeFragment == null) {
        mHomeFragment = HomeFragment.newInstance();
    }
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    if (mHomeFragment.isAdded()) {
        fragmentTransaction.show(mHomeFragment);
    } else {
        fragmentTransaction.add(mHomeFragment, tag);
    }
    fragmentTransaction.commitAllowingStateLoss();
}


 

你可能感兴趣的:(Android,Android,Fragment)