Use backstack with ViewPager

Sebastian picture Sebastian · Oct 3, 2012 · Viewed 9.2k times · Source

I am using a ViewPager to implement swiping in my android app. However, I would like the previous fragment to be shown when the user uses the back button instead of ending the activity. Is there any way to do that? Thanks Sebastian

Answer

refactor picture refactor · Jul 20, 2018

Overriding below method in Fragment Activity should solve your issue.

@Override
public void onBackPressed() {
    if (mViewPager.getCurrentItem() == 0) {
        // If the user is currently looking at the first step, allow the system to handle the
        // Back button. This calls finish() on this activity and pops the back stack.
        super.onBackPressed();
    } else {
        // Otherwise, select the previous step.
        mViewPager.setCurrentItem(mViewPager.getCurrentItem() - 1);
    }
}