0

I would like to use FragmentStatePagerAdapter or FragmentPagerAdapter to be able to swipe through 3 different fragments. Each of the individual fragment is from a different class. I am not quite sure where I should create the new object. Should it be done in the getItem function? Most of the examples I see are using the same type of fragment.

private class SimplePagerAdapter extends FragmentPagerAdapter  {

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

    @Override
    public Fragment getItem(int position) {
        switch( position ) {
            case 0: return (Fragment) new myFragmentType1(); // ?
            case 1: return (Fragment) new myFragmentType2(); // ?
            default: return (Fragment) new myFragmentType3(); // ?
        }
    }

    @Override
    public int getCount() {
        return 3;
    }
}

Thank you in advance!

1 Answers1

0

Don't do it in getItem(). That method gets called whenever the adapter needs to populate the Pager and you will end up creating new Fragments. Do it in the Adapter constructor. I usually keep them in an ArrayList, then reference them using the position attribute in getItem(). This also helps if you need to use the getItemPosition() method as well, as you can then look up the position in the ArrayList with the matching fragment.

David C Adams
  • 1,953
  • 12
  • 12