问题
I'm using google navigation drawer library from the following link... https://github.com/Arasthel/GoogleNavigationDrawerMenu
See code below:
mDrawer.setOnNavigationSectionSelected(new GoogleNavigationDrawer.OnNavigationSectionSelected() {
@Override
public void onSectionSelected(View v, int i, long l) {
Fragment fragment = null;
switch (i) {
case 0:
// fragment = new HomeFragment();
break;
case 1:
fragment = new NewsFragment();
break;
case 2:
fragment = new TransferFragment();
break;
case 3:
fragment = new BlogsFragment();
break;
case 4:
fragment = new FixturesFragment();
break;
case 5:
fragment = new BestXIFragment();
break;
case 6:
fragment = new FeedFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.main, fragment).commit();
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
});
My fragments are using async task and whenever I switch between these fragments the async task is loading again.
So How can I save the state of the fragment?
回答1:
Instead of creating new fragment every time you can keep an array of fragments and just return the same object:
mDrawer.setOnNavigationSectionSelected(new GoogleNavigationDrawer.OnNavigationSectionSelected() {
Fragment[] fragments ={new HomeFragment(),new NewsFragment(), new TransferFragment(), new BlogsFragment(),new FixturesFragment() , new BestXIFragment(),new FeedFragment()};
@Override
public void onSectionSelected(View v, int i, long l) {
if (fragment[i] != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.main, fragments[i]).commit();
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
});
来源:https://stackoverflow.com/questions/24882470/how-to-save-state-of-fragment-in-navigation-drawer