There is a navigation drawer and fragments, how to make the previous fragment return when the arrow is pressed, and not exit the application?

  • Add fragments to the transaction when creating. - Sergey Gornostaev
  • More details please - Big_Energy

1 answer 1

Changing fragments, stack them:

mFragmentManager.beginTransaction().replace(R.id.frame_container, fragment) .addToBackStack("").commit(); 

Then handle pressing the "Back" button in your Activity :

 @Override public boolean dispatchKeyEvent(KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN) { switch (event.getKeyCode()) { case KeyEvent.KEYCODE_BACK: // Здесь нужно доставать предыдущий фрагмент return true; } } return super.dispatchKeyEvent(event); } 

To get the previous snippet use mFragmentManager.popBackStack();