I'm using a navigatin drawer to switch betwen two fragments. I use setRetainInstance(true) in both fragments, but it's not working. In FeedFragment there is a simple textView and in the MapFragment there is a google map.
FeedFragment and MapFragment (same code inside onCreate)
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
MainActivity
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
Fragment fragment = null;
if (id == R.id.nav_feed) {
if (feedFragment == null)
feedFragment = new FeedFragment();
fragment = feedFragment;
} else if (id == R.id.nav_mapa) {
if (mapFragment == null)
mapFragment = new MapFragment();
fragment = mapFragment;
}
try {
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
} catch (Exception e) {
e.printStackTrace();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
EDIT
I found a solution. I change the fragment in the replace function to feedFragment, or mapFragment.
if (id == R.id.nav_feed) {
if (feedFragment == null)
feedFragment = new FeedFragment();
fragmentManager.beginTransaction().replace(R.id.content_frame, feedFragment).commit();
} else if (id == R.id.nav_mapa) {
if (mapFragment == null)
mapFragment = new MapFragment();
fragmentManager.beginTransaction().replace(R.id.content_frame, mapFragment).commit();
}