'Replaceable Fragment in ViewPager2

I have a Fragment (lets call it RootFragment) containing aViewPager2 that switches between two fragments on tab1 and tab2. Only considering the fragment on tab2, it starts as showing Fragment 1, which contains a button. When the button is pressed, I'd like Fragment 2 to show up over Fragment 1 and added to the backstack for that page.

diagram

Here is the code for the RootFragment.

public class RootFragment extends Fragment {

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.root_fragment, container, false);

        ViewPager2 pager = view.findViewById(R.id.myPager);
        FragmentStateAdapter pagerAdapter = new ScreenSlidePagerAdapter(this);
        pager.setAdapter(pagerAdapter);

        TabLayout tabLayout = view.findViewById(R.id.myTabLayout);
        new TabLayoutMediator(tabLayout, pager, (tab, position) -> {
            if (position == 0) {
                tab.setText("tab1");
            } else {
                tab.setText("tab2");
            }
        }).attach();

        return view;
    }

    private static class ScreenSlidePagerAdapter extends FragmentStateAdapter {
        public ScreenSlidePagerAdapter(Fragment fragment) {
            super(fragment);
        }

        @NonNull
        @Override
        public Fragment createFragment(int position) {
            if (position == 0) {
                return new FragmentTab1(); // don't care about this right now
            } else {
                return new Fragment1();
            }
        }

        @Override
        public int getItemCount() {
            return 2;
        }
    }
}

My initial thought would be to use a FragmentManager transaction in Fragment1 when the button is pressed to add Fragment 2 and update the backstack. However, I'm unsure what the correct container argument would be to use in that transaction.

Is the best way to achieve this to create a dummy Fragment just containing a FragmentContainerView as the Fragment instantiated by the ViewPager2's getFragment, have that fragment initially replace itself with Fragment1, then use that parent container for the transaction? Or is there a better way that avoids adding a dummy Fragment?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source