之前實現Fragment的切換都是用replace方法實現ide
public void startFragmentAdd(Fragment fragment) { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.main_layout, fragment, fragment.getClass().getName()) .commit(); }
// fragment的切換 private void startFragmentAdd(Fragment fragment) { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager .beginTransaction(); if (current_fragment == null) { fragmentTransaction.add(R.id.main_layout, fragment).commit(); current_fragment = fragment; } if (current_fragment != fragment) { // 先判斷是否被add過 if (!fragment.isAdded()) { // 隱藏當前的fragment,add下一個到Activity中 fragmentTransaction.hide(current_fragment) .add(R.id.main_layout, fragment).commit(); } else { // 隱藏當前的fragment,顯示下一個 fragmentTransaction.hide(current_fragment).show(fragment) .commit(); } current_fragment = fragment; } }