I have some fragments in my program, and I can replace each fragment by clicking on it using this code. my problem is this: these fragments are low for loading and after clicking on each fragment create a new one from it and cause reloading after clicking on the fragment. how to save fragment contents or state and prevent 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();
}
}
AFTER UPDATE
after answering this question @Vikram Ezhil I initialized fragmentsboth fragmentTAGto the constructor and changed the @Vikram Ezhil code to this code below, 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();
}
user4108483
source
share