title: How to correctly handle multiple fragment change in Android
body: <p>Assume I have 4 fragments A B C and D.</p>
  
  <p>A and B are major fragments, C and D are minor.</p>
  
  <p>I use navigation drawer to switch fragments.</p>
  
  <p>A is the default starting fragment.</p>
  
  <p>I want to achieve following features but cannot figure out how to play with the fragment manager and transactions.</p>
  
  <ol>
  <li>A -> B or B -> A, replace current fragment, do not push backstack, but I want to keep the current fragment status (e.g. list view position) after navigate back</li>
  <li>A/B -> C/D, add C/D on top of A/B, using back button to navigate back to A/B.</li>
  <li>C -> D or D -> C, replace current fagment</li>
  <li>C/D -> A/B, remove current fragment C/D and show A/B</li>
  </ol>
  
  <p>Is the only way to implement this function that I should write some complicated function for switching the fragments (and also need to keep what is current fragment and what is the wanted target fragment)?</p>
  
  <p>Is there better way out? </p>
  
  <hr>
  
  <p>According to @DeeV 's answer, I came out with something like following.</p>
  
  <p>LocalBrowse and WebsiteExplore are main fragments while Settings and About are sub fragments.</p>
  
  <p>It seems to work fine but still a little bit ugly, any better idea?</p>
  
  <pre><code>private void switchToFragment(Class&lt;?&gt; targetFragmentClz) {
      if(mCurrentFagment!=null &amp;&amp; mCurrentFagment.getClass().equals(targetFragmentClz)) {
          return;
      }
      BaseFragment targetFragment = null;
      FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
      if(targetFragmentClz.equals(LocalBrowseFragment.class)
              || targetFragmentClz.equals(WebsiteExploreFragment.class)) {
          if(mCurrentFagment instanceof SettingsFragment //mCurrentFragment will not be null this time
                  || mCurrentFagment instanceof AboutFragment) {
              transaction.remove(mCurrentFagment);
          }
          if(mCurrentMainFagment==null || !mCurrentMainFagment.getClass().equals(targetFragmentClz)) {
              targetFragment = (BaseFragment) Fragment.instantiate(this, targetFragmentClz.getName());
              targetFragment.setHasOptionsMenu(true);
              transaction.replace(R.id.ac_content_frame_main, targetFragment);
              mCurrentMainFagment = targetFragment;
          }
      } else {
          targetFragment = (BaseFragment) Fragment.instantiate(this, targetFragmentClz.getName());
          targetFragment.setHasOptionsMenu(true);
          getSupportFragmentManager().popBackStackImmediate();
          transaction.replace(R.id.ac_content_frame_sub, targetFragment)
                     .addToBackStack(null);
      }
  
      transaction.commit();
      mCurrentFagment = targetFragment;
  }
  </code></pre>