How to set a ViewPager inside a Fragment

Starting in Android 4.2, there are nested fragments.http://developer.android.com/about/versions/android-4.2.html#NestedFragments The support library now also includes support for this for older Android versions.

So you can do something like this:

@Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    ViewPager mViewPager = (ViewPager) view.findViewById(R.id.viewPager);
    mViewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
    }

Full implementation available here: https://github.com/marcoRS/nested-fragments/tree/master/src/com/burnside/digital/nestedfragments


You must use getChildFragmentManager() instead of getSupportFragmentManager() to get the FragmentManger inside a Fragment. But you should not use FragmentStatePagerAdapter rather than FragmentPagerAdapter.