片段再次创建,android?

时间:2015-06-11 12:26:52

标签: android fragment navigation-drawer fragmenttransaction

我的活动中有一个导航抽屉,并在点击的抽屉项目上添加了碎片

添加片段

Fragment fragment = null;
    switch (position) {
        case 0:
            fragment = new Fragment()1;
            break;
        case 1:
            fragment =  new Fragment()2;
            break;
        case 2:
            fragment =  new Fragment()3;
            break;
        case 3:
            fragment =  new Fragment()4;
            break;
        case 4:
            fragment =  new Fragment()5;
            break;
        default:
            break;
    }

    if (fragment != null) {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction ft = fragmentManager.beginTransaction();
        ft.replace(R.id.frame_container, fragment);
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        ft.addToBackStack(null);
        ft.commit();
        closeDrawer();
    } else {
        Logger.e("MainActivity", "Error in creating fragment");
    }

每当我从一个片段切换回另一个片段时,视图再次膨胀,因为之前的片段被破坏并且正在再次创建。

如何阻止它重新创建?

1 个答案:

答案 0 :(得分:1)

Fragment fragment1 = null;
Fragment fragment2 = null;
Fragment fragment3 = null;
Fragment fragment4 = null;
Fragment fragment5 = null;
    switch (position) {
        case 0:
        if (fragment1 == null) {
            fragment1 = new Fragment()1;
        }   
            break;
        case 1:
            if (fragment2 == null) {
            fragment2 = new Fragment()2;
            }
            break;
        case 2:
            if (fragment3 == null) {
            fragment3 = new Fragment()3;
            }
            break;
        case 3:
            if (fragment4 == null) {
            fragment4 = new Fragment()4;
            }   
            break;
        case 4:
            if (fragment5 == null) {
            fragment5 = new Fragment()5;
            }
            break;
        default:
            break;
    }

    if (fragment != null) {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction ft = fragmentManager.beginTransaction();
        ft.replace(R.id.frame_container, fragment);
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        ft.addToBackStack(null);
        ft.commit();
        closeDrawer();
    } else {
        Logger.e("MainActivity", "Error in creating fragment");
    }