Question

I've read some posts similar to my problem and the most similar problem is here: Strange onPause(), onResume() behaviour in fragments

I'm using FragmentPagerAdapter to create a tabs fragment. I have 3 fragments A, B, and C.

  • When application started, I saw fragment A and B onCreateView() called.
  • When I changed to tab B, I saw fragments C onCreateView() called.
  • When I changed to tab C nothing happened.
  • When I changed back to tab B, I save fragments A onCreateView called.
  • I never seen fragments B onCreateView() called.

Here is my FragmentPagerAdapter implementation:

public class TabsPagerAdapter extends FragmentPagerAdapter {

private static final int TOTAL_TABS = 3;

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

@Override
public Fragment getItem(int index) {

    switch (index) {
        case 0:
            // Top Rated fragment activity
            return new ImageFragment();
        case 1:
            // Games fragment activity
            return new CameraFragment();
        case 2:
            // Movies fragment activity
            return new WebFragment();
    }

    return null;
}

@Override
public int getCount() {
    // get item count - equal to number of tabs
    return TOTAL_TABS;
}

@Override
public int getItemPosition(Object object) {
    return super.getItemPosition(object);
}

}

I hope someone can help me with simple explanation about behaviour of my fragments

Was it helpful?

Solution 3

I suppose you are using an Action Bar, what you described is the normal behaviour of the adapter: when there is the need to display a fragment the next fragments in the list will be pre-loaded (by default, but you can change this). So at first you need A, so it will load just B because there is nothing 'at the left' of the A, when you switch to B, just the C fragment will be pre-loaded because A is already present, finally when you go to C the adapter don't need to pre-load anything because there is nothing 'at the right' of the C and it already has B.

Hope it helps.

OTHER TIPS

  • When application started, I saw fragment A and B onCreateView() called.

The thing with the ViewPagerAdapter is, that it will always instantiate the items next to the one which is currently visible.

When you start the App the adapter will create A and B. B will always be available with only 3 Tabs.

  • Currently on Tab A: [ A ][ B ] is instantiated
  • Currently on Tab B: [ A ][ B ][ C ] is instantiated
  • Currently on Tab B: [ B ][ C ] is instantiated

TabView - when you switch tabs then onResume never gets called after first time, then you have to use the setUserVisibleHint to perform the operation like update/refresh

@Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top