How do I use FragmentPagerAdapter to have tabs with different content?

Create the adapter:

class MyPagerAdapter extends FragmentPagerAdapter {
        public List<String> fragmentsA; 

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
            fragmentsA = fragments;
        }

        @Override
        public Fragment getItem(int position) {
            //return MyFragment.newInstance();
            return Fragment.instantiate(context, fragmentsA.get(position));

        }

        @Override
        public CharSequence getPageTitle(int position) {
            //return CONTENT[position % CONTENT.length].toUpperCase();
            return mEntries.get(position % CONTENT.length).toUpperCase();
        }

        @Override
        public int getCount() {
           // return CONTENT.length;
            return mEntries.size();
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }
    }

Each fragment belongs to different classes.

So you have to define a fragment list (These go to the main FragmentActivity) :

static MyPagerAdapter adapter;

and fill it with the fragments:

fragments.add(ConnectionFragment.class.getName());
fragments.add(DataFragment.class.getName());
fragments.add(Tab3.class.getName());
//..etc

Then you have to add the fragments to the adapter like this:

 pager = (ViewPager)findViewById(R.id.viewpager);
 adapter = new MyPagerAdapter(getSupportFragmentManager());
 pager.setAdapter(adapter);

The MyPagerAdaper will go through all the fragments contained by the fragments list, then it will instantiate each of them.


In your FragmentPagerAdapter#getItem method, do not create object of the Fragments. You need to return the Fragment in the following way -

return Fragment.instantiate(context, ConnectionFragment.class.getName());

This means that the method will look like this -

public class SectionsPagerAdapter extends FragmentPagerAdapter {

  public SectionsPagerAdapter(FragmentManager fm) {
    super(fm);  
  }

  @Override
  public Fragment getItem(int position) {
    Fragment fragment =null;
    switch (position) {
        case 0:
            fragment = Fragment.instantiate(context, ConnectionFragment.class.getName());
            break;
        case 1:
            fragment = Fragment.instantiate(context, DataFragment.class.getName());
            break;              
        case 2:
            fragment = Fragment.instantiate(context, GraphFragment.class.getName());
            break;          }
    return fragment;    
  }

  @Override
  public int getCount() {
    // Show 3 total pages.
    return 3;
  }
}