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);
}
Copyright Notice:Content Author:「shivani gupta」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/37915563/not-to-reload-the-fragment-once-loaded-android