//首先需要先實(shí)例好n個(gè)全局Fragment
//private Fragment currentFragment=new Fragment();(全局)
private FragmentTransaction switchFragment(Fragment targetFragment) {
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
if (!targetFragment.isAdded()) {
//第一次使用switchFragment()時(shí)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;
}
在點(diǎn)擊切換Fragment時(shí)調(diào)用:
@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();
}
}
如果fragment數(shù)據(jù)更新了怎么辦?
onHiddenChanged()