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
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!