shivani gupta shivani gupta - 5 months ago 58
Android Question

Not to reload the fragment once loaded-ANDROID

In my

Android
app I have 6 fragments which are replaced one by one on clicking item in navigation drawer. My problem is that fragment are loaded again and again when clicking on navigation drawer items. I don not want my fragment to reload again and again. Instead I want them to remain in their previous state when switching from fragment to fragment.
Addbacktostack()
is not working.please tell me some other way to do it:

My code is:

@Override
public void onDrawerItemSelected(View view, int position) {
row_view = view;
displayView(position);

}

private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new Fragmenta();
title = "aaaa";
toolbar_title.setText(title);
break;
case 1:
fragment = new Fragmentb();
title = "Introduction";
toolbar_title.setText(title);
break;
case 2:
fragment = new Glossary();
title = "Glossary";
toolbar_title.setText(title);
break;
case 3:
fragment = new SettingsFragment();
title = "Settings";
toolbar_title.setText(title);
break;
case 4:
fragment = new FeedbackFragment();
title = "Feedback";
toolbar_title.setText(title);
break;
case 5:
fragment = new Fragmentc();
title = "cc";
toolbar_title.setText(title);
break;

default:
break;
}



if (myfragmentstate != null) { // This is always null
//Restore the fragment's instance
fragment = getSupportFragmentManager().getFragment(myfragmentstate, "mContent");
Log.i("sadfas","fragment"+fragment);

}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.replace(R.id.container_body,fragment); //always reloads a fragment and i donot want this
fragmentTransaction.commit();
toolbar_title.setText(title);

}
}



@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.i("MicroRAE","instanmce save"+fragment);
getSupportFragmentManager().putFragment(outState, "mContent", fragment);
}

Answer

I have found a very good solution :

String backStateName = fragment.getClass().getName();

    FragmentManager fragmentManager = getSupportFragmentManager();
    boolean fragmentPopped = fragmentManager.popBackStackImmediate (backStateName, 0);

    if (!fragmentPopped){ //fragment not in back stack, create it.
        FragmentTransaction fragmentTransaction = fragmentManager
                .beginTransaction();
        fragmentTransaction.replace(R.id.container_body,fragment);
        fragmentTransaction.addToBackStack(backStateName);
        fragmentTransaction.commit();
        toolbar_title.setText(title);
    }