Eugene Eugene - 9 months ago 38
Android Question

Why it is not possible to use ViewPager within a Fragment? It actually is

There are information that it is impossible to use

within a
in many sources like "The Busy Coders Guide for Android Developers" by Mark Murphy, or posts like this on SO. I'm confused because I don't have such a problem and I successfully use
within my
. The only distinction is that I instantiate a
not in
method but in
. And everything works perfectly fine.

So the question is - may be I just don't know something and this is not recommended for some reason to make UI instantiations in
? But again - everything works just fine.

Here is the listing of the class and xml:


public class ViewPagerFragment extends Fragment {

static final int NUM_ITEMS = 2;

private ViewPagerAdapter mAdapter;
private ViewPager mPager;

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.view_pager_fragment, container, false);

public void onActivityCreated(Bundle savedInstanceState) {

mAdapter = new ViewPagerAdapter(getFragmentManager());

mPager = (ViewPager) getView().findViewById(;

public static class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager fm) {

public Fragment getItem(int num) {
if (num == 0) {
return new ItemsListFragment();
} else {
return new FavsListFragment();

public int getCount() {
return NUM_ITEMS;


<LinearLayout xmlns:android=""



Answer Source

UPDATE: Since this answer was originally written, you now can have nested fragments, which means it is possible to have a ViewPager use fragments for pages and be in a fragment itself. This sample project demonstrates the technique.

I now return you to your regularly-scheduled answer, presented in its entirety...

Quoting myself from the book:

The simplest way to use a ViewPager is to have it page fragments in and out of the screen based on user swipes. This only works if the ViewPager itself is not contained within a fragment, as you cannot have fragments nested inside of other fragments.

Quoting Dianne Hackborn:

Nested fragments are not currently supported. Trying to put a fragment within the UI of another fragment will result in undefined and likely broken behavior.

It is perfectly possible to put a ViewPager inside a Fragment, so long as the contents of the ViewPager do not themselves contain fragments. Since the concrete implementations of PagerAdapter supplied by the Android Support package use fragments, you have to roll your own fragment-less PagerAdapter to put the ViewPager in a fragment.

I will endeavor to make this point clearer in the next edition of the book (unless you're British, in which case I'll endeavour to make this point clearer :-).