I have several fragments which are organized with a ViewPager. I add an addOnPageChangeListener to the ViewPager in MainActivity's onCreate method which gives the position of the selected fragment.
Even though I prevent the fragments from destroying themselves with stating a setOffscreenPageLimit, I still haven't figured out how to access fragments from MainActivity, as simply using findViewById returns null object exceptions.
What I want to do:
I would like to access elements of fragments, e.g. layouts and scrollviews, in the OnPageListener of the ViewPager:
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageSelected(int i) {
if(i == 0) {
// Do something with the first fragment.
} else if(i == 1) {
// Do something with the second fragment.
}
}
}
The ViewPager uses a FragmentPagerAdapter:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return Fragment1.newInstance(position);
case 1:
return Fragment2.newInstance(position);
case 2:
return Fragment3.newInstance(position);
case 3:
return Fragment4.newInstance(position);
default:
throw new IllegalArgumentException();
}
}
@Override
public int getCount() {
return 4;
}
}
Which is added like this:
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager.setAdapter(mSectionsPagerAdapter);
~
Or should I change my approach?
If accessing fragments cannot be achieved with this design, what could be an effective alternative route?
I've tried to implement ViewPager.onPageChangeListener in the custom ViewPager, but it didn't seem to be a good option.
I could deal with the elements in their respective fragments, but this is a tedious process and hard to maintain, which I the reason I look for a way to handle them simultaneously.
I know similar questions have been asked before, but I didn't find a solution in them.