Return to second fragment from other fragments

Viewed 59

I have 3 fragments in my MainActivity and I have set the second fragment as the default fragment (when you launch the app, you will see the second fragment).

I want to implement a code similar to OnBackPressed() that when the user presses the back button of phone and he/she is in 1st or 3rd fragment, instead of quiting the app, the application return to the second app.

MainActivity

public class MainActivity extends AppCompatActivity {
    private ViewPager2 mPager; 
    private FragmentStateAdapter pagerAdapter;
    private int num_page = 3;
    private CircleIndicator3 mIndicator;

    @Override
    protected void onCreate(Bundle savedInstanceState)  {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        mPager = findViewById(R.id.viewpager);
        pagerAdapter = new MyAdapter(this, num_page);
        mPager.setAdapter(pagerAdapter);
    
        mIndicator = findViewById(R.id.indicator);
        mIndicator.setViewPager(mPager);
        mIndicator.createIndicators(num_page,0);
    
        mPager.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);
        mPager.setCurrentItem(1000, false);
        mPager.setOffscreenPageLimit(1);
        mPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
                if (positionOffsetPixels == 0) {
                    mPager.setCurrentItem(position);
                }
            }
    
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                mIndicator.animatePageSelected(position%num_page);
            }
        });
    
        mPager.setPageTransformer(new ViewPager2.PageTransformer() {
            @Override
            public void transformPage(@NonNull View page, float position) {
                float myOffset = position;
                if (mPager.getOrientation() == ViewPager2.ORIENTATION_HORIZONTAL) {
                    if (ViewCompat.getLayoutDirection(mPager) == ViewCompat.LAYOUT_DIRECTION_RTL) {
                    } else {
                    }
                } else {
                }
            }
        });
    }
}
    page.setTranslationY(myOffset);
    page.setTranslationX(-myOffset);
    page.setTranslationX(myOffset);

MyAdapter

public class MyAdapter extends FragmentStateAdapter {
    public int mCount;

    public MyAdapter(FragmentActivity fa, int count) {
        super(fa);
        mCount = count;
    }
    
    @NonNull
    @Override
    public Fragment createFragment(int position) {
        int index = getRealPosition(position);
        if (index == 0) return new FragFirst();
        else if (index == 1) return new FragSecond();
        else return new FragThird();
    }
    
    @Override
    public int getItemCount() {
        return 2000;
    }

    public int getRealPosition(int position) {
        return position % mCount;
    }

FragFirst, FragSecond and FragThird

public class FragFirst extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup, container, Bundle savedInstanceState) {
        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.frame_1p, container, false);
    }
}

Thanks

2 Answers

Generally, if you addToBackStack its transaction when you go to the 1st or the 3rd, then you can back to the 2nd when onBackPressed.

fragmentManager
        .beginTransaction()
        .replace(R.id.mainContainer, thirdFragment, ThirdFragment.TAG)
        .addToBackStack(null)
        .commit();

According to the Google's official training, you can define onBackPressed in the Activity like:

@Override
public void onBackPressed() {
    if (viewPager.getCurrentItem() == 1) {
        // If the user is currently looking at the 2nd page, allow the system to handle the
        // Back button. This calls finish() on this activity and pops the back stack.
        super.onBackPressed();
    } else if (viewPager.getCurrentItem() == 0 || viewPager.getCurrentItem() == 2) {
        // Select the 2nd page.
        viewPager.setCurrentItem(1);
    } else {
        // There is no such a page number.
        throw new IllegalArgumentException();
    }
}

(* In addition to the above, the official training uses FragmentActivity rather than AppCompatActivity. I don't know whether it relates this problem or not.)

Related