How to set a ViewPager inside a Fragment

Gilberto Ibarra picture Gilberto Ibarra · Sep 29, 2013 · Viewed 79.8k times · Source

I need to place a ViewPager inside of a fragment, but I have two fragments, Fragment 1 is my MENU, and Fragment 2 I want to use as a ViewPagerIndicator.

But a fragment can't have another fragment... what do I need to do for that?

enter image description here

Answer

Ryan S picture Ryan S · Sep 29, 2013

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