I am trying to convert my IOS app to android, and I am a little new in android. My app navigates between fragments generally with the navigation drawer. When I am at fragment A, and then go to fragment B, and then press the back button, with the codes below it goes back to fragment A. However, when I go to fragment A with the back button, it loads again from the beginning. Is there a way that it goes back to previous fragment without loading the class again that the previous info in the fragment will be shown? It would be great if anyone could help about this?
This is the code when the back button is pressed:
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount()>0) {
fm.popBackStack();
}
else {
System.out.println("no more back");
}
}
}
This is how I navigate between fragments:
usersFragment fragment = new usersFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
EDIT:
Use
fragmentTransaction.hide(getFragmentManager().findFragmentByTag("yourTag"));
fragmentTransaction.add(R.id.fragment_container, fragment);
instead of
fragmentTransaction.replace(R.id.fragment_container, fragment);
Its because replace remove current fragment and add next fragment. So when coming back it recreate previous fragment again.