title: Replace a Fragment in a ViewPager using FragmentPagerAdapter
body: <p>I am using a ViewPager with 4 pages, and I'm looking for an efficient way to replace/switch between fragments in each page.</p>
  
  <p>This is the interaction pattern that I'm trying to create: </p>
  
  <ol>
  <li>User presses a button on a page that currently holds fragment A</li>
  <li>Fragment A is swapped out for some new fragment B</li>
  <li>The user does some work in fragment B, and then presses a button when he/she is done</li>
  <li>Fragment B is removed, and is replaced by fragment A (the original fragment)</li>
  </ol>
  
  <p>I've found a way to do this, but it seems to have significant flaws.  The solution involves removing the original fragment, and then overriding <code>getItemPosition</code> (essentially the method described in this <a href="https://stackoverflow.com/a/9127423/812868">related question</a>):</p>
  
  <pre><code>//An array to keep track of the currently visible fragment in each page
  private final Fragment[] activeFragments= new Fragment[4];
  
  public void openFragmentB(ViewPager pager, int position) {
  
      startUpdate(pager);
  
      //Remove the original fragment
      FragmentTransaction transaction = fragmentManager.beginTransaction();
      transaction.remove(activeFragments[position]);
      transaction.commit();
  
      //Create a new tile search fragment to replace the original fragment
      activeFragments[position] = FragmentB.newInstance();
      pageStates[position] = PageState.STATE_B;
  
      finishUpdate(pager);
      notifyDataSetChanged();
  }
  
  @Override
  public int getItemPosition(Object object) {
  
      //If the main fragment is not active, return POSITION_NONE
      if(object instanceof FragmentA) {
          FragmentA a = (FragmentA) object;
          if(pageStates[a.getPosition()] != PageState.STATE_A) {
              return POSITION_NONE;
          }
      }
  
      //If the secondary fragment is not active, return POSITION_NONE
      if(object instanceof FragmentB) {
          FragmentB b = (FragmentB) object;
          if(pageStates[b.getPosition()] != PageState.STATE_B) {
              return POSITION_NONE;
          }
      }
  
      return POSITION_UNCHANGED;
  }
  </code></pre>
  
  <p>This method works, but has undesirable side effects.  Removing the fragment and setting it's position to POSITION_NONE causes the fragment to be destroyed.  So when the user finishes using FragmentB, I would need to create a new instance of FragmentA instead of reusing the original fragment.  The main fragments in the pager (FragmentA in this example) will contain relatively large database backed lists, so I want to avoid recreating them if possible.</p>
  
  <p>Essentially I just want to keep references to my 4 main fragments and swap them in and out of pages without having to recreate them every time.  Any ideas?</p>