0

I have a PagerAdapter which creates 3 fragments. In the MainActivity I set the ViewPager like this:

    ViewPager pager = (ViewPager) findViewById(R.id.pager);
    pager.setOffscreenPageLimit(2);
    pager.setAdapter(new PagerAdapter(getSupportFragmentManager()));

the pager.setOffScreenPageLimit(2) is from here https://stackoverflow.com/a/11852707/1662033, to make sure OnViewCreated is called once for each fragment.

Here is my PagerAdapter class:

public class PagerAdapter extends FragmentPagerAdapter {

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

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "Home";
            case 1:
                return "Live";
            case 2:
                return "Gallery";
            default:
                return null;
        }
    }

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

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return new HomeFragment();
            case 1:
                return new LiveFragment();
            case 2:
                return new GalleryFragment();
            default:
                return null;
        }
    }
}

In the current code: all of the fragments's onCreateView, onActivityCreated etc are called once, at the beginning and that's it.

The issue I am having is - in one of the fragments (LiveFragment) I have a custom view which connects to a camera and shows the live stream.

What I want is - to inflate the view of LiveFragment only when the user navigates to the fragment, instead of how its now - its inflated at the beginning with the other fragments.

Is there a way to call onCreateView only when fragment is chosen?

Community
  • 1
  • 1
Ofek Agmon
  • 5,040
  • 14
  • 57
  • 101

1 Answers1

0

FragmentPagerAdapter creates all the Fragments and has all of them in memory at all time. i.e. All your Fragments are created only once and you can navigate around them.

FragmentStatePagerAdapter creates and has only 3 Fragments (the current Fragment and the left and right Fragments to the current one) in memory at any given time, by default. You cannot reduce that number. However, you can increase the number Fragments in memory by using the viewpager.setOffScreenPageLimit().

Since you have only 3 Fragments, all your 3 fragments are created when the Viewpager is initialised. You can track which Fragment is currently visible on the screen using viewpager.addOnPageChangeListener(). Using this you can change the View of your LiveFragment from dummy one to actual View only when the Fragment is currently visible.

Bob
  • 13,447
  • 7
  • 35
  • 45