title: Using backstack and back button in viewpager
body: <p>I'm using a viewpager to swipe between fragments and would like the back button to navigate to the previously viewed fragment rather than ending the activity. Sorry if this is a duplicate of <a href="https://stackoverflow.com/questions/12712917/use-backstack-with-viewpager">this question</a> however I didn't find the answer very helpful. Obviously onBackPressed needs to be overridden, but I don't know how to get and display the correct fragment. I assume that I should use the fragmentmanager's backstack, but <code>getSupportFragmentManager().getBackStackEntryCount()</code> always returns 0. Do I need to manually add fragments to the backstack using <code>FragmentTransaction.addToBackStack()</code>? If so, where would I add this in my adapter?</p>
  
  <p>Here is the code for my activity,</p>
  
  <pre><code>public class PagerActivity extends FragmentActivity {
  
  ArrayList&lt;Sale&gt; sales;
  MyAdapter mAdapter;
  ViewPager mPager;
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
  
      Intent it = getIntent();
      this.sales = (ArrayList&lt;Sale&gt;) it.getExtras().get("sales");
      int position = it.getExtras().getInt("position");
  
      ActionBar actionBar = getActionBar();
      actionBar.setDisplayHomeAsUpEnabled(true);
  
      setContentView(R.layout.fragment_pager);
      mAdapter = new MyAdapter(getSupportFragmentManager());
      mPager = (ViewPager) findViewById(R.id.pager);
      mPager.setAdapter(mAdapter);
      mPager.setCurrentItem(position);
  
  }
  
  public class MyAdapter extends FragmentPagerAdapter {
      public MyAdapter(FragmentManager fragmentManager) {
          super(fragmentManager);
      }
  
      @Override
      public int getCount() {
          return sales.size();
      }
  
      @Override
      public void destroyItem(ViewGroup container, int position, Object object) {
          super.destroyItem(container, position, object);
      }
  
      @Override
      public Fragment getItem(int position) {
          SalesThumbFragment frag = new SalesThumbFragment();
          return frag.newInstance(sales.get(position));
      }
  }
  
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
      switch (item.getItemId()) {
      case android.R.id.home:
          finish();
          return true;
      }
      return super.onOptionsItemSelected(item);
  }
  
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.sales_controller, menu);
      return true;
  }
  
  @Override
  public void onBackPressed() {
    if(getSupportFragmentManager().getBackStackEntryCount() != 0) {
      getSupportFragmentManager().popBackStack();
    } else {
  
      super.onBackPressed();
    }
  }
  
  
  }
  </code></pre>