Fragment created again, android?

143 views Asked by At

I have a navigation drawer in my activity and add the fragments on drawer item clicked

For adding the fragment

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");
    }

Whenever I switch back from one fragment to another fragment the view is inflated again as in previous fragment was destroyed and it is being created again.

How can I stop it from being recreated?

1

There are 1 answers

0
Neela On
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");
    }