// getSupportFragmentManager()应用于v4包;
fragmentManager=getSupportFragmentManager();
fragmentTransaction=fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.framelayout_main,mainFragment);
fragmentTransaction.commit();
mTempFragment = mainFragment;
运用replace方法做替换,被替换的fragment会被注销。如:A replace替换成B,A被销毁,而B被创建;
运用replace做替换肯定不符合要求,为了填补这个不足我们用show,hide,add代替replace;add添加fragment,add不会注销之前的fragment,所以用hide隐藏被替换的fragment,show显示已经被添加fragment;
private void switchFragment(Fragment fragment) {
if (fragment != mTempFragment) {
Log.e(TAG, "fragment != mTempFragment");
if (!fragment.isAdded()) {
fragmentTransaction=fragmentManager.beginTransaction();
fragmentTransaction.hide(mTempFragment);
fragmentTransaction.add(R.id.framelayout_main,fragment);
fragmentTransaction.commit();
} else {
fragmentTransaction=fragmentManager.beginTransaction();
fragmentTransaction.hide(mTempFragment);
fragmentTransaction.show(fragment);
fragmentTransaction.commit();
}
mTempFragment = fragment;
}
}