title: Android: Switching Fragments and the Backstack
body: <p>After struggling to make my simple fragment program work, I have not found any solution to the following: I manage two Fragments in my main activity: FragmentNeedle and FragmentPlot. Only one should appear at a time. The user has two bottons where he can select which fragment he wants to display. Also, when the FragmentPlot is showing, the user should be able to navigate back to the FragmentNeedle by pressing the back key. This is my Code:</p>
  
  <pre><code>public void onButtonPlotPressed()
  {
      FragmentManager manager = getSupportFragmentManager();      
      mPlotFragment = (PlotFragment) manager.findFragmentByTag(PlotFragment.class.getSimpleName());
  
      if(mPlotFragment == null)
      {
          mPlotFragment = new PlotFragment();
          FragmentTransaction ft = manager.beginTransaction();            
          ft.replace(R.id.main_layout_center, mPlotFragment, PlotFragment.class.getSimpleName());                                                 
          ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);                               
          ft.addToBackStack(null);
          ft.commit();        
          manager.executePendingTransactions();   
      }
  
  public void OnButtonNeedlePressed()
  {
      FragmentManager manager = getSupportFragmentManager();
  mFragmentNeedle = (FragmentNeedle) manager.findFragmentByTag(FragmentNeedle.class.getSimpleName()); 
  
  
      FragmentTransaction ft = manager.beginTransaction();        
      if(mFragmentNeedle == null)
      {
          mFragmentNeedle= new FragmentNeedle();
  
          ft.replace(R.id.main_layout_center, mFragmentNeedle,    FragmentNeedle.class.getSimpleName());                                  
          ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);                    
          ft.commit();            
          manager.executePendingTransactions();   
      }   
  
  
  }
  </code></pre>
  
  <p>When the PlotFragment is shown, and I press back, I return to the NeedleFragment. But now when I try to change to Plot Fragment by pressing the UI button, it will keep showing the PlotFragment. If I remove the line ft.addToBackStack(), the switching between fragments works fine by pressing the buttons on the UI, but then I cannot go back with the back key. What am I doing something wrong?</p>