Fragment切换
-
replace,加回退栈,Fragment不销毁,但是切换回销毁视图和重新创建视图。
-
replace,不加回退栈,Fragment销毁掉。
-
hide、show,Fragment不销毁,也不销毁视图。隐藏和显示不走生命周期。
replace
1
2
3
4
5
6
7
8
9
private FragmentTransaction switchFragment(Fragment targetFragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if (!targetFragment.isAdded()) {
transaction.add(R.id.fragmentShow,targetFragment,targetFragment.getClass().getName());
}
transaction.replace(R.id.fragmentShow,targetFragment);
currentFragment = targetFragment;
return transaction;
}
hide,show
1
2
3
4
5
6
7
8
9
10
11
12
13
private FragmentTransaction switchFragment(Fragment targetFragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if (!targetFragment.isAdded()) {
//第一次使用switchFragment()时currentFragment为null,所以要判断一下
if (currentFragment != null) {
transaction.hide(currentFragment);
}
transaction.add(R.id.fragmentShow,targetFragment,targetFragment.getClass().getName());
} else {
transaction.hide(currentFragment).show(targetFragment);
}
currentFragment = targetFragment;
return transaction;