title: Fragment back-stack management on android
body: <p>I have several fragments. They transition using slid-in animations. MainFragment-> Fragment2 -> Fragment3. </p>
  
  <p>1) I want to clear backstack when user reach MainFragment, leaving just that fragment in the stack. </p>
  
  <p>2) In some cases I want to remove the previous item in the stack. Say when user press back button and move from fragment3 = > fragment2.</p>
  
  <p>I have shown my code below. If I use that method, the fragment transitions animations get messed up. I am not sure how to implement the second requirement.</p>
  
  <p>Another question is when I remove fragments from backstack do they get disposed?</p>
  
  <pre><code>private void replace(Fragment fragment )    
  {
  if(fragment == null) return;
  
              FragmentTransaction fragmentTransaction = fragmentManager
                      .beginTransaction();
              fragmentTransaction.setCustomAnimations(R.anim.fragment_enter,
                      R.anim.fragment_exit);
  
              fragmentTransaction.replace(R.id.fragment, fragment);
              fragmentTransaction.addToBackStack(fragment.toString());
  
              fragmentTransaction.commit();
  
  
              if(fragment instanceof MainFragment)
                  clearBackStack();
  }
  </code></pre>
  
  <hr>
  
  <pre><code>public void clearBackStack() {
  
          if (fragmentManager.getBackStackEntryCount() &gt; 0) {
              FragmentManager.BackStackEntry first = fragmentManager.getBackStackEntryAt(0);
              fragmentManager.popBackStack(first.getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
          }
      }
  </code></pre>