androidandroid-viewpagerback-stack

Use backstack with ViewPager


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


Solution

  • Override the functionality of your Activity:

    public class Activity extends Activity
    {
        @Override
        public void onBackPressed()
        {
            // do stuff
            myFragment.onBackPressed();
        }
    }
    
    public class Fragment extends Fragment
    {
    
        public void onBackPressed()
        {
            // do stuff
        }
    }