FragmentPagerAdapter instantiateItem working with Fragments?

Kitesurfer picture Kitesurfer · Jun 11, 2012 · Viewed 8.4k times · Source

i try to get my FragmentPagerAdapter working, but the examples are a bit to easy for real life :

@Override
public Object instantiateItem(final ViewGroup container, final int position)
{
    final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    int resId = 0;
    switch (position)
        {
        case 0:
            resId = R.layout.favorites_fragment;
            break;
        case 1:
            resId = R.layout.nearby_list_fragment;
            break;
        default:
            throw new IllegalArgumentException("Index cant be mapped to fragement:" + position);
        }

    final View view = inflater.inflate(resId, null);

    viewPager.addView(view, 0);

    return view;
}

As i'm want to use Fragments im already confused my this method as all example i could find inflate a view instead of create fragment there. How to do this ?

PS: Im using the ActionBarSherlock lib 4.1...

Thanks, Jens

Answer

Nikolay Elenkov picture Nikolay Elenkov · Jun 11, 2012

What exactly are you trying to do? Show the definition of your class. You have to extend FragmentPagerAdapter and implement public abstract Fragment getItem(int position) to return your fragments. Do not override instantiateItem() it already does the right thing in FragmentPagerAdapter.