1. 程式人生 > >FragmentTransaction替換fragment後生命週期會再執行一次

FragmentTransaction替換fragment後生命週期會再執行一次

FragmentTransaction呼叫add方法會再次呼叫fragment的生命週期

FragmentTransaction呼叫show方法就可以解決了

FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
if(current!=null){
    fragmentTransaction.hide(current);
}
current = fragment;
if (fragment != null && fragment.isAdded()) {
    fragmentTransaction.show(fragment);
} else {
    fragmentTransaction.add(R.id.container, fragment);
}
fragmentTransaction.commit();

current為當前顯示的fragment