title: Android : Return to previous fragment on back press
body: <p>I have implemented Navigation Drawer which is a subclass of Activity. I have many fragments in my application. My question goes here</p>
  
  <p>Imagine there are 3 fragments :</p>
  
  <p>Fragment_1 : Fragment_2 : Fragment_3</p>
  
  <p>When I start my application, Fragment_1 is loaded
  When I click on some components on Fragment_1, I'm navigated to Fragment_2 and so on..</p>
  
  <p>So it's like</p>
  
  <p>Fragment_1 > Fragment_2 > Fragment_3</p>
  
  <p>When I press back key from Fragment_2, I'm navigated back to Fragment_1
  But when I press back key from Fragment_3, I'm navigated back to Fragment_1 (instead of Fragment_2)</p>
  
  <p>I want something like this in my application on Back Key press</p>
  
  <p>Fragment_1 &lt; Fragment_2 &lt; Fragment_3</p>
  
  <p>I have used Fragment, FragmentManager, FragmentTransaction as follows :  </p>
  
  <pre><code>MyFragment fragment = new MyFragment();
  FragmentManager fragmentManager = getFragmentManager();
  
  fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).addToBackStack(null)commit();
  </code></pre>
  
  <p>and I tried overriding onBackPressed() in my MainActivity :</p>
  
  <pre><code>@Override
  public void onBackPressed() {
  
  
          getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
          int count = getFragmentManager().getBackStackEntryCount();
          if (count == 0)
                 super.onBackPressed();
      }
  </code></pre>