title: Android Reorder Fragment Backstack
body: <p>I have a number of pages/fragments listed in my navigation drawer, the user is likely to switch between these frequently and I want them in the backstack so that they can navigate back, but I only want one instance of each fragment in the backstack so that the user doesn't not have to press back an insane number of times to exit the app. I can't figure out how to effectively 'reorder' the backstack' without pages getting removed.</p>
  
  <p>Currently when I change page I was using this code to change the fragment and make sure it's only in the back stack once</p>
  
  <pre><code>  if (mFragMgr == null) {
        mFragMgr = getSupportFragmentManager();
    }
  
    String backStateName = fragmentDescriptor.name();
    boolean fragmentPopped = mFragMgr.popBackStackImmediate(backStateName, 0);
    if (!fragmentPopped){
        mFragMgr.beginTransaction()
        .remove((Fragment) mFragment)
        .replace(R.id.content_frame, (Fragment) mFragment)
        .addToBackStack(backStateName)
        .commit();
    }
  </code></pre>
  
  <p>I use this code in onBackPressed</p>
  
  <pre><code>  @Override
    public void onBackPressed() {
        if (mFragMgr.getBackStackEntryCount() &gt; 0) {
            mFragMgr.popBackStackImmediate();
        } else {
            super.onBackPressed();
        }
    }
  </code></pre>
  
  <p>This works but it means it removes pages I don't want removed. Example:</p>
  
  <p>When my user visits 6 pages in the order <code>A &gt; B &gt; C &gt; D &gt; E &gt; C</code> because I'm doing a remove I expected the following stack: </p>
  
  <pre><code>                            [E]    [C]
                       [D]    [D]    [E]
                [C]    [C]    [C]    [D]
         [B]    [B]    [B]    [B]    [B]
  [A] -&gt; [A] -&gt; [A] -&gt; [A] -&gt; [A] -&gt; [A]
  </code></pre>
  
  <p>But what I actually get is the following - it pops everything up to the element that matches the name, this is regardless of whether I include the ".remove((Fragment) mFragment)" or not - (<em>I've already realised now that remove isn't affecting the backstack, so no need to point that out</em>):</p>
  
  <pre><code>                            [E]
                       [D]    [D]
                [C]    [C]    [C]    [C]
         [B]    [B]    [B]    [B]    [B]
  [A] -&gt; [A] -&gt; [A] -&gt; [A] -&gt; [A] -&gt; [A]
  </code></pre>
  
  <p>If I don't use a name and instead use null when adding to the backstack I get the following:</p>
  
  <pre><code>                                   [C]
                              [E]    [E]   
                       [D]    [D]    [D]    
                [C]    [C]    [C]    [C]   
         [B]    [B]    [B]    [B]    [B]  
  [A] -&gt; [A] -&gt; [A] -&gt; [A] -&gt; [A] -&gt; [A] 
  </code></pre>
  
  <p>How can I get the behaviour I expect? Is it possible at all or am I going to need to record the changes myself and skip the backstack altogether?</p>