Android tutorial. How to replace fragments inside a ViewPager

This is a migrated post from my former blog

I’ve developed a little example app about replacing a Fragment by another one inside a ViewPager. Also, if you navigate between them it’s possible to keep the backstack:


The key is to put the ViewPager inside a Fragment that acts as a container and that we’ll use as a reference. Inside the PageAdapter class:

// PagerAdapter class
public class SlidePagerAdapter extends FragmentPagerAdapter {
    public SlidePagerAdapter(FragmentManager fm) {
    public Fragment getItem(int position) {
         * IMPORTANT: This is the point. We create a RootFragment 
         * acting as a container for other fragments
        if (position == 0)
           return new RootFragment();
           return new StaticFragment();
    public int getCount() {
        return NUM_ITEMS;

In the RootFragment class:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
    /* Inflate the layout for this fragment */
    View view = inflater.inflate(R.layout.root_fragment, container, false);
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
     * When this container fragment is created, we fill it with our first
     * "real" fragment
    transaction.replace(, new FirstFragment());
    return view;

And finally, inside the FirstFragment class, we can include links to another fragments:

btn.setOnClickListener(new OnClickListener() { 
    public void onClick(View v) {
        FragmentTransaction trans = getFragmentManager().beginTransaction();
         * IMPORTANT: We use the "root frame" defined in
         * "root_fragment.xml" as the reference to replace fragment
        trans.replace(, new SecondFragment());
         * IMPORTANT: The following lines allow us to add the fragment
         * to the stack and return to it later, by pressing back

The complete example is in Github for complete free use and also there’s an example app on Google Play.