I am trying to create a bottom navigation menu similar to WhatsApp, Viber etc. where I am switching between fragments. I got it somewhat working fragmentManager replacing the fragments, but as it turned out this re-creates the replaced fragments when I want to come back to one of the menu pages I have previously visited, changed etc.
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment fragment = null;
switch (item.getItemId()) {
case R.id.navigation_discover:
fragment = findFragment(RPageFragment.getTAG());
if(fragment == null){
fragment = RPageFragment.newInstance();
mFragmentManager.beginTransaction().add(R.id.fragment_container, fragment, fragment.getTag()).commit();
}
break;
case R.id.navigation_booked:
fragment = findFragment(MapViewFragment.getTAG());
if(fragment == null){
fragment = MapViewFragment.newInstance();
mFragmentManager.beginTransaction().add(R.id.fragment_container, fragment, fragment.getTag()).commit();
}
break;
case R.id.navigation_me:
fragment = findFragment(ProfilePageFragment.getTAG());
if(fragment == null){
fragment = ProfilePageFragment.newInstance();
mFragmentManager.beginTransaction().add(R.id.fragment_container, fragment, fragment.getTag()).commit();
}
break;
}
//Invalid menu option
if (fragment == null)
return false;
mFragmentManager.beginTransaction().replace(R.id.fragment_container,fragment).commit();
return true;
}
Is there any way to swap the fragments while preserving their view, state etc. similar to the way Whatsapp works ? (For example I have a mapView Fragment and I would like when I come back to it, to be showing the way I left it instead of recreating the mapView)