in my program i have some Fragments and i can replace each Fragment by click on that with this code. my problem is this: those fragments are low to load and after click on each Fragments create new from it and cause of load again after clicked on fragment. how to save fragment content or state and prevent to reload?
@Override
public void onNavigationDrawerItemSelected(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new InfoFragment();
break;
case 1:
fragment = new ParentOtoFragment();
break;
case 2:
fragment = new ParentProFragment();
break;
case 3:
fragment = new SupportFragment();
break;
case 4:
fragment = new AboutFragment();
break;
}
if (fragment != null){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container,fragment).commit();
}
}
POST UPDATE
after reply to this topic by @Vikram Ezhil i'm initials fragments
and fragmentTAG
into constructor and change @Vikram Ezhil code to this below code, my problem is solved.
@Override
public void onNavigationDrawerItemSelected(int position) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
if (getSupportFragmentManager().findFragmentByTag(fragmentTAGS[position]) == null) {
fragmentTransaction.add(R.id.container, fragments[position], fragmentTAGS[position]);
}
for (int i = 0; i < fragments.length; i++) {
if (i == position) {
fragmentTransaction.show(fragments[i]);
} else {
if (getSupportFragmentManager().findFragmentByTag(fragmentTAGS[position]) != null) {
fragmentTransaction.hide(fragments[i]);
}
}
}
fragmentTransaction.commit();
}