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?