4

I have 3 fragments in a viewpager (using compatibility library), the first one is shown when the app loads. the 2nd and 3rd pages are a bit CPU intensive, so I would like to load their content only when user swipes to them first.

for this I have implemented ViewPager.OnPageChangeListener and overrode onPageSelected to call an onResume in the Fragment

public void onPageSelected(int position) {
    getItem(viewPager.getCurrentItem()).onResume();
}

in the Fragments onResume is the following:

@Override
public void onResume() {
    super.onResume();

    if ((MainActivity) getActivity() != null && ((MainActivity) getActivity()).pager != null && ((MainActivity) getActivity()).pager.getCurrentItem() == 1) {
        doCpuIntensiveLoading();
    }
}

to prevent it from loading when instantiated and not visible, but to load when pager's getCurrentItem() returns the fragment's id.

but! when I scroll to the page getActivity() returns null although the fragment's menu is populated and calling load from menu is working.

please let me know if you need more details.

materemias
  • 131
  • 1
  • 2
  • 7

0 Answers0