0
public class MyPagerAdapter extends FragmentPagerAdapter {

    private List<Fragment> fragmentList;
    /**
     * Use this method to add pages in order
     */
    private void initializeFragmentList() {
        fragmentList = new ArrayList<>();
        fragmentList.add(LocationCriteriaFragment.newInstance("FirstFragment", "Instance 1"));
        fragmentList.add(NeighborhoodRatingFragment.newInstance("", ""));
        fragmentList.add(PropertyCriteriaFragment.newInstance("", ""));
        fragmentList.add(ExteriorPhotoEnhancedFeaturesFragment.newInstance());
        fragmentList.add(InteriorPhotoEnhancedFeaturesFragment.newInstance());
    }
    public MyPagerAdapter(android.support.v4.app.FragmentManager fm) {
        super(fm);
        initializeFragmentList();
    }

    public List<Fragment> getFragmentList() {
        return fragmentList;
    }

    @Override
    public Fragment getItem(int pos) {
        return fragmentList.get(pos);
    }

    @Override
    public int getCount() {
        return fragmentList.size();
    }
}

I'm using this as an adapter for a ViewPager. Is this a good approach for getting fragment references easily based on positions? Will it give a huge unexpected crash during some part of Fragment/Activity lifecycle?

Veneet Reddy
  • 2,707
  • 1
  • 24
  • 40
  • I see no problems. It's all good. If you want code-review, you may post it on http://codereview.stackexchange.com. – Gurupad Mamadapur Feb 08 '17 at 12:41
  • I disagree with my previous comment, FragmentPagerAdapter is better suited in this case instead of FragmentStatePagerAdapter. – Gurupad Mamadapur Feb 08 '17 at 12:53
  • 1
    In my opinion using this approach you will not be able to take advantage of the "Lazy initialization of fragment objects" as your fragments will be created the moment your adapter is created which is fine unless your fragments are heavy in that case it will create a noticeable lag while initial rendering. Have a look here https://developer.android.com/reference/android/support/v4/app/FragmentPagerAdapter.html – raktale Feb 08 '17 at 12:53
  • @raktale This makes sense. Thanks! – Veneet Reddy Feb 08 '17 at 13:18

1 Answers1

0

Try to use FragmentPagerStateAdapter insteadof FragmentPagerAdapter.

FragmentPagerAdapter stores the previous data which is fetched from the adapter while FragmentStatePagerAdapter takes the new value from the adapter everytime it is executed

Jd Prajapati
  • 1,953
  • 13
  • 24