Android使得Fragment 切換時不從新實例化

之前實現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();
}
 replace()方法只是在上一個Fragment再也不須要時採用的簡便方法。所以,每次切換的時候,Fragment都會從新實例化,從新加載數據。
若是要實現Fragment 切換時不從新實例化,正確的切換方式是add(),切換時hide()當前,add()另外一個Fragment;再次切換時,只需hide()當前,show()另外一個。
// 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;
    }
}
相關文章
相關標籤/搜索