//首先需要先实例好n个全局Fragment
private Fragment currentFragment=new Fragment();(全局)
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.fragment, targetFragment,targetFragment.getClass().getName());
} else {
transaction
.hide(currentFragment)
.show(targetFragment);
}
currentFragment = targetFragment;
return transaction;
}
使用
@Override
public void onTabSelected(@IdRes int tabId) {
if (tabId == R.id.tab_one){
switchFragment(first).commit();
}
if (tabId == R.id.tab_two){
switchFragment(second).commit();
}
if (tabId == R.id.tab_three){
switchFragment(third).commit();
}
}