Replace Fragment inside a ViewPager

后端 未结 18 1351
别那么骄傲
别那么骄傲 2020-11-22 00:26

I\'m trying to use Fragment with a ViewPager using the FragmentPagerAdapter. What I\'m looking for to achieve is to replace a fragment, positioned

18条回答
  •  死守一世寂寞
    2020-11-22 01:00

    tl;dr: Use a host fragment that is responsible for replacing its hosted content and keeps track of a back navigation history (like in a browser).

    As your use case consists of a fixed amount of tabs my solution works well: The idea is to fill the ViewPager with instances of a custom class HostFragment, that is able to replace its hosted content and keeps its own back navigation history. To replace the hosted fragment you make a call to the method hostfragment.replaceFragment():

    public void replaceFragment(Fragment fragment, boolean addToBackstack) {
        if (addToBackstack) {
            getChildFragmentManager().beginTransaction().replace(R.id.hosted_fragment, fragment).addToBackStack(null).commit();
        } else {
            getChildFragmentManager().beginTransaction().replace(R.id.hosted_fragment, fragment).commit();
        }
    }
    

    All that method does is to replace the frame layout with the id R.id.hosted_fragment with the fragment provided to the method.

    Check my tutorial on this topic for further details and a complete working example on GitHub!

提交回复
热议问题